Try using the Python web framework Tornado Part 1

Introduction

I've been playing with Tornado recently, so I'll show you how to use it.

This time, it's almost an official Top rehash. Please look forward to it next time. If you have any questions or requests, we will answer them.

Execution environment

My execution environment is as follows, but I think that there is no problem if it is an environment where Python works.

Related article

What is Tornado

Tornado is a web framework / asynchronous communication library written in Python and has the following features.

From now on, we will handle everything from installation to Hello, world.

Installation of Tornado

Install Tornado with pip.

$ pip install tornado

If you have not installed pip, you should install it by referring to the following site.

If you don't want to use pip, drop tar.gz and use setup.py as usual.

tar xvzf tornado-3.2.2.tar.gz
cd tornado-3.2.2
python setup.py build
sudo python setup.py install

Hello, world Once installed, all you have to do is import, write the appropriate code, and listen. Here, as the simplest example, let's display the string "Hello, world" in the browser. To display Hello, world, save and execute the following code in an appropriate directory with an appropriate name (server.py in this case).

Source code

server.py


#!/bin/env python
# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Start-up

Just give python a script.

$ python server.py

Nothing is displayed in the terminal, but if you access it with a browser in this state, "Hello, world" will be displayed.

Browsing

helloworld.png

Let's play a little more

It's boring just to display the string, so at least I'll try to return the html file. Prepare the style sheet and HTML file, and rewrite server.py as follows. With this knowledge, you should be able to build an ancient website that returns properly styled static pages.

Directory structure

Prepare style.css in the static directory and index.html in the templates directory.

$ tree --charset=x
.
|-- server.py
|-- static
|   `-- style.css
`-- templates
    `-- index.html

Source code

The main changes in server.py are as follows.

server.py


#!/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

application = tornado.web.Application([
    (r"/", MainHandler)
    ],
    template_path=os.path.join(os.getcwd(),  "templates"),
    static_path=os.path.join(os.getcwd(),  "static"),
)

if __name__ == "__main__":
    application.listen(8888)
    print("Server is up ...")
    tornado.ioloop.IOLoop.instance().start()

style.css


body {
  font-family:'Lucida Grande', 'Hiragino Kaku Gothic ProN', 'Hiragino Kakugo ProN W3', "MS Gothic", sans-serif;
  width: 80%;
  margin: 0 auto;
}
p {
  color:#BEAF71;
  font-size:200%;
}

index.html


<!DOCTYPE html>
<html>
  <head>
    <title>Hello, world</title>
    <link rel="stylesheet" href="{{ static_url("style.css") }}"/>
  </head>
  <body>
    <div id="container">
      <div id="main">
        <p>Hello, world</p>
      </div>
    </div>
  </body>
</html>

Start-up

$ python server.py
print("Server is up ...")

Browsing

You can see that the HTML is certainly returned.

helloworld.png helloworld.png

Recommended Posts

Try using the Python web framework Tornado Part 1
Try using the Python web framework Tornado Part 2
Try using the Python web framework Django (2) --Look at setting.py
Try using the web application framework Flask
Try using the Python web framework Django (1)-From installation to server startup
Try using the Python Cmd module
Try using the Wunderlist API in Python
Try using the Kraken API in Python
I tried the Python Tornado Testing Framework
Django python web framework
Introduction to Tornado (1): Python web framework started with Tornado
Try using the BitFlyer Ligntning API in Python
Python: Try using the UI on Pythonista 3 on iPad
Try using the collections module (ChainMap) of python3
Try using Tweepy [Python2.7]
Try using the DropBox Core API in Python
Explanation of the concept of regression analysis using python Part 2
Cut a part of the string using a Python slice
(Python) Try to develop a web application using Django
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Explanation of the concept of regression analysis using Python Part 1
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
[Python] Try using Tkinter's canvas
Try using Kubernetes Client -Python-
Try using SQLAlchemy + MySQL (Part 1)
Try using the Twitter API
Try using SQLAlchemy + MySQL (Part 2)
Web scraping using Selenium (Python)
Try using the PeeringDB 2.0 API
Python beginners publish web applications using machine learning [Part 1] Introduction
Try a similar search for Image Search using the Python SDK [Search]
[Part.2] Crawling with Python! Click the web page to move!
[CleanArchitecture with Python] Part2: Frameworks & Drivers Layer: Introducing the Web
Operate your browser using the Selenium Web Driver Python bindings
Try using Pillow on iPython (Part 1)
Try using Pleasant's API (python / FastAPI)
Hit the web API in Python
Try using Pillow on iPython (Part 3)
Extract the targz file using python
Try using Python argparse's action API
Install Python framework django using pip
Try using Leap Motion in Python
Try using Amazon DynamoDB from Python
Try to analyze online family mahjong using Python (PART 1: Take DATA)
I made a scaffolding tool for the Python web framework Bottle
Visualize your pocket money files with the Python web framework Dash
Try using FireBase Cloud Firestore in Python for the time being
Introducing the BOT framework Minette for Python
GUI creation in python using tkinter part 1
Try mathematical formulas using Σ with python
Behind the flyer: Using Docker with Python
Try using the $ 6 discount LiDAR (Camsense X1)
Try using the HL band in order
[Beginner] Python web scraping using Google Colaboratory
Try using the camera with Python's OpenCV
Try using Dialogflow (formerly API.AI) Python SDK #dialogflow
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
Tweet using the Twitter API in Python