Home >Backend Development >Python Tutorial >Web Development in Python: Tornado in Action

Web Development in Python: Tornado in Action

PHPz
PHPzOriginal
2023-06-11 10:49:441476browse

With the rise of the Internet, Web development has become more and more important in the IT field. Python, as a high-level programming language that focuses on development efficiency, has also become popular in the field of web development. Among them, Tornado, a lightweight network framework, has a unique position in Python. It uses an asynchronous IO-based method, which makes it process concurrent requests faster than the traditional synchronous IO method. This article will introduce the methods and techniques of using Tornado for web development in Python through practical combat.

1. Installation and basic use of Tornado

First, we need to install Tornado in the local environment. It can be installed via pip:

pip install tornado

After the installation is complete, we can use Tornado to build a simple web server.

import tornado.ioloop
import tornado.web

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

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

In the above code, we define a MainHandler class inherited from tornado.web.RequestHandler, which can handle GET requests sent by the client. In the constructor, we use the self.write() method to return a message to the client. Next, we define the make_app() function, which creates a tornado.web.Application object. In the constructor of this object, we map the route to the MainHandler class we defined and return it. Finally, we create an Application object in the if name == "__main__" code block, listen on the local 8888 port, and start the IOLoop loop. Visit http://localhost:8888 in your local browser and you will see the "Hello, world" message.

2. Asynchronous IO in Tornado

As an efficient Web framework, Tornado’s asynchronous IO-based mechanism enables it to quickly respond to client requests. In traditional synchronous IO operations, each request needs to wait for the completion of the previous request before proceeding to the next request. In asynchronous IO operations, when an IO operation is initiated, the thread will not be blocked forever, but will return immediately and continue to execute the next request. This mechanism allows the web server to handle multiple requests at the same time, thereby improving the system's concurrent processing capabilities.

First, let’s look at an example of synchronous IO.

import tornado.ioloop
import tornado.web
import time

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

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

In the above code, we simulate an operation that takes 5 seconds to complete. If we access the server with a browser, we will find that we will wait until the request is processed.

Next, let’s look at an example of using asynchronous IO operations.

import tornado.ioloop
import tornado.gen
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        yield tornado.gen.sleep(5)
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

In the above code, we use the tornado.gen.coroutine modifier and use the yield statement to implement asynchronous IO operations. This means that before executing the yield statement, the processor will immediately return and process the next request, and the result will not be returned to the client until the asynchronous operation is completed.

3. Multi-threading and multi-process in Tornado

In addition to its asynchronous IO capabilities, Tornado can also improve the concurrent processing capabilities of the server through multi-threading or multi-process technology. In Tornado, we can use two methods to implement multi-threading or multi-process processing:

1. Use tornado.process.fork_processes() to enable multi-process mode. This method will automatically set the multi-process mode based on the number of CPU cores. Each process is assigned a corresponding port.

import tornado.ioloop
import tornado.web
import tornado.process

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

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.process.fork_processes()
    tornado.ioloop.IOLoop.current().start()

In the above code, we use the tornado.process.fork_processes() method to enable multi-process mode, so that we can make full use of the advantages of CPU parallel processing.

2. Use tornado.concurrent.futures.ThreadPoolExecutor() to enable multi-threading mode.

import tornado.ioloop
import tornado.web
import tornado.concurrent
import concurrent.futures

class MainHandler(tornado.web.RequestHandler):
    executor = concurrent.futures.ThreadPoolExecutor()

    @tornado.concurrent.run_on_executor
    def my_background_task(self):
        # 执行一些耗时的IO操作
        return result

    @tornado.gen.coroutine
    def get(self):
        result = yield self.my_background_task()
        self.write(result)

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

In the above code, we use tornado.concurrent.futures.ThreadPoolExecutor() to enable multi-threading mode, and use the @tornado.concurrent.run_on_executor modifier to hand over the my_background_task() method to the thread pool to execute. This way, we can handle multiple IO operations simultaneously in a single thread.

4. Summary

This article allows readers to understand the use of Tornado for Web in Python by introducing the basic use of Tornado, asynchronous IO operations, multi-threading and multi-process technology, and usage examples. Development methods and techniques. Tornado's efficiency, simplicity and flexibility make it one of the important tools for web development in Python. Although Tornado is not suitable for all Web scenarios, in some scenarios with high performance and concurrency requirements, Tornado will show its superior performance.

The above is the detailed content of Web Development in Python: Tornado in Action. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn