Tornado-02, Write the first tornado program

Time:2019-10-9

1. Introduction to Tornado

Tornado is a powerful and extensible Web server written in Python. It is robust enough to handle severe network traffic, but lightweight enough to create and write, and can be used in a large number of applications and tools.

The installation of tornado is also very simple. Pip installation can be used directly:pip install tornado

2. Tornado routing mapping

We already know what Tornado is. Now let’s see what it can do. Let’s start by writing a simple Web application using Tornado.

Tornado is a framework for writing responses to HTTP requests. As a programmer, your job is to write handlers that respond to specific HTTP requests. The following is a basic example of a fully functional Tornado application:
Create a new Python file namedstart1Add some code to the file

start1.py


import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("hello ")

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

if __name__ == "__main__":
    Application. listen (8000)  Here you need to set up port forwarding to forward the host's 8000 port to the virtual machine's 8000 port.
    tornado.ioloop.IOLoop.instance().start()

Click tool – > start SSH session
In the terminal below pycharm, enter the following command to execute the PY file


workon py3env
cd tornado_1
ls
python start1.py

Tornado-02, Write the first tornado program


Then type the corresponding IP address and routing in the browser address bar
* Note that the address bar is filled in with the IP address (that is, ubuntu)ifconfigThe address shown) and then add ‘:‘plus port number
For example, your IP is192.43.22.132The port is9000
That’s how the address bar should be filled in.192.43.22.132:9000*


Tornado-02, Write the first tornado program


This is a simple, basic example. Next, let’s look at a more complex example.

start2.py


Import tornado. httpserver # Help start tornado server
Import tornado. ioloop # Open tornado loop, wait in the background
Import tornado. options # command line read settings
Import tornado. web# RequestHandler and Application are in this module

From tornado. options import define, options # define is used to define the default port number

# Define a default port
define("port", default=9000, help="run on the given port", type=int)


# Define a class for event handling
class IndexHandler(tornado.web.RequestHandler):
    Def get (self): # This is get method
        Self. write ('abc') # Write the string ABC into the page  


if __name__ == "__main__":
    tornado.options.parse_command_line()

    app = tornado.web.Application(  
        handlers=[  
        (r "/", IndexHandler), # routing mapping calls the IndexHandler class when accessing the routing/
        ]
    )
    http_server = tornado.httpserver.HTTPServer(app)
    Http_server.listen (options.port) # listen on this port
    Tornado. ioloop. IOLoop. instance (). start ()# Start the service

Turn off start1.py in execution(Ctrl + C
Update this new file to Ubuntu
Execute the start2.py file again
Then enter ip: 9000 in the browser address bar (we just changed the value of port)
It is shown below.


Tornado-02, Write the first tornado program


Adding different paths after ports can do different things through routing mapping.

Add the following code to start2.py


# Adding routing mapping
(r"/aaa", AaaHandler),

# Write corresponding classes
class AaaHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('aaa')
    
# With different mappings, requirements can be met

Tornado-02, Write the first tornado program

In the above code,self.write()That is output, which can be exported to the browser.
Note that the output of write is the serialized object of Python object, JSON object

3. Input and output of Tornado’s project structure

In the above code, self. write () is the output, which can be exported to the browser.

But if you want input, you can use a query string.
Add some code to start2.py

# Adding routing mapping
(r"/gre", GreHandler),

# Adding processing classes
class GreHandler(tornado.web.RequestHandler):
    def get(self):
        GRE = self. get_argument ('aaa','hello') # Gets the value of AAA on the web page by default to hello
        self.write(gre + ',frindely user!')

Here get_argumentation can get the parameter input in the browser address bar.

Default case


Tornado-02, Write the first tornado program

Parametric case

Change the parameter to 123
The format of parameter input is post-routing +?+variable assignment


Tornado-02, Write the first tornado program

Use get_arguments to get a list of query strings.

Note: Write cannot serialize a list, but a dictionary is OK.

Recommended Today

How to use eolinker to scan GitLab code comments to automatically generate API documentation?

Preface: After you’ve written your code, write all kinds of parameter annotations into the API documentation to facilitate subsequent docking and testing. This process is usually cumbersome, and it would be very convenient if you had a tool that could read the code annotations and directly generate the API documentation.I’ve been using eolinker all my […]