Home >Backend Development >Python Tutorial >Introduction to asynchronous and coroutineization of developing Tornado website in Python
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()
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!