Home > Backend Development > Python Tutorial > Introduction to asynchronous and coroutineization of developing Tornado website in Python

Introduction to asynchronous and coroutineization of developing Tornado website in Python

不言
Release: 2018-10-19 17:22:26
forward
2511 people have browsed it
This article brings you an introduction to asynchronous and coroutine development of Tornado websites in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Tornado has two ways to change the synchronization process:

Asynchronous: Use the @tornado.web.asynchronous decorator for the RequestHandler processing function to change the default synchronization mechanism Change to asynchronous mechanism. This method has expired.

Coroutineization: Use the @tornado.gen.coroutine decorator for the RequestHandler processing function to change the default synchronization mechanism to the coroutine mechanism.

1. Asynchronousization

This method has expired and will not be described again. Use @tornado.gen.coroutine instead.

2. Coroutineization

Tornado coroutine combines the advantages of synchronous processing and asynchronous processing, making the code clear and easy to understand, and can adapt to the high speed of massive clients. Concurrent requests.

Code:

import tornado.web
import tornado.httpclient
from tornado.web import Application
import tornado.ioloop
class MainHandler(tornado.web.RequestHandler):


    @tornado.gen.coroutine
    def get(self):
        http=tornado.httpclient.AsyncHTTPClient()
        response=yield http.fetch("http://www.baidu.com")
        self.write(response.body)

if __name__ == '__main__':
    app=Application([
        ("/",MainHandler)
    ])
    app.listen("8888")
    tornado.ioloop.IOLoop.current().start()
Copy after login

The key technical points of coroutine are as follows:

  • Use tornado.gen.coroutine to decorate MainHandler’s get() and post () and other processing functions.

  • Use asynchronous objects to handle time-consuming operations, such as AsyncHTTPClient in this example.

  • Call the yield keyword to obtain the processing result of the asynchronous object.

The above is the detailed content of Introduction to asynchronous and coroutineization of developing Tornado website in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template