Home  >  Article  >  Backend Development  >  Implementation code of HelloWorld in Tornado in Python

Implementation code of HelloWorld in Tornado in Python

不言
不言forward
2018-10-16 16:13:352455browse

This article brings you the implementation code of HelloWorld in Tornado in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Example: HelloWorld

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),

    ])

def main():
    app=make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

if __name__=="__main__":
    main()

Browser input link: http://localhost:8888

The page displays:

Hello World

The following is line by line Analyze what the above code does:

  1. First introduce the ioloop and web classes in the tornado package through the import statement. These two classes are the basis of Tornado programs.

  2. Implement a web.RequestHandler subclass and overload the get() function in it. This function is responsible for processing the HTTP GET request corresponding to the RequestHandler. This example outputs "Hello world" through the self.write() function.

  3. The make_app() function is defined, which returns a web.Application object. The first item of this object is used to define the route map for the Tornado program. This example maps access to the URL to the RequestHandler subclass MainHandler.

  4. Use the web.Application.listen() function to specify the port that the server listens on.

  5. Use tornado.ioloop.IOLoop.current().start() to start IOLoop. This function will always run without exiting and is used to handle all client requests.

The above is the detailed content of Implementation code of HelloWorld in Tornado in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete