About Python Web framework --Tornado

Tornado on the entry of reading this article, very well written:

https://zhuanlan.zhihu.com/p/37382503

 

Tornado is a Python web framework library and an asynchronous network, using a non-blocking network I / O.

Tornado can be divided into four main parts:

  • web framework
  • HTTP client and server to achieve
  • Asynchronous network library
  • Coroutine library

WSGI is the Web Server Gateway Interface acronym.

Real-time web features necessary to provide a long connection is idle most of the time for each user, in a conventional synchronous web server, which means to provide a thread for each user, of course, the cost of each thread is very expensive.

In order to minimize the overhead caused by concurrent connections, Tornado used a single-threaded event loop mode. This means that all the application code should be asynchronous non-blocking , because only one operating at the same time to be effective.

Know almost back-end and palm reading should be adopted this framework.

 

The following provides quick help recall code :( pi computing services)

# pi.py
import json
import math
import redis
import tornado.ioloop
import tornado.web

class FactorialService(object):

    def __init__(self, cache):
        self.cache = cache
        self.key = "factorials"

    def calc(self, n):
        s = self.cache.hget(self.key, str(n))
        if s:
            return int(s), True
        s = 1
        for i in range(1, n):
            s *= i
        self.cache.hset(self.key, str(n), str(s))
        return s, False

class PiService(object):

    def __init__(self, cache):
        self.cache = cache
        self.key = "pis"

    def calc(self, n):
        s = self.cache.hget(self.key, str(n))
        if s:
            return float(s), True
        s = 0.0
        for i in range(n):
            s += 1.0/(2*i+1)/(2*i+1)
        s = math.sqrt(s*8)
        self.cache.hset(self.key, str(n), str(s))
        return s, False

class FactorialHandler(tornado.web.RequestHandler):

    def initialize(self, factorial):
        self.factorial = factorial

    def get(self):
        n = int(self.get_argument("n") or 1)
        fact, cached = self.factorial.calc(n)
        result = {
            "n": n,
            "fact": fact,
            "cached": cached
        }
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        self.write(json.dumps(result))

class PiHandler(tornado.web.RequestHandler):

    def initialize(self, pi):
        self.pi = pi

    def get(self):
        n = int(self.get_argument("n") or 1)
        pi, cached = self.pi.calc(n)
        result = {
            "n": n,
            "pi": pi,
            "cached": cached
        }
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        self.write(json.dumps(result))

def make_app():
    cache = redis.StrictRedis("localhost", 6379)
    factorial = FactorialService(cache)
    pi = PiService(cache)
    return tornado.web.Application([
        (r"/fact", FactorialHandler, {"factorial": factorial}),
        (r"/pi", PiHandler, {"pi": pi}),
    ])

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

Because the two redis Handler need to use, so we will redis separate it out, passing in the parameter. Further Handler initialize function parameters can be passed, a dictionary registered route when any parameter can be passed, and the key for the dictionary and the corresponding parameter name. We run python pi.py, open the browser access http://localhost:8888/pi?n=200, you can see the browser output {"cached": false, "pi": 3.1412743276, "n": 1000}, this value is already very close to the ratio of the circumference.

 

The following :( know almost from the very well written)

https://zhuanlan.zhihu.com/p/37382503

Tornado:Hello, World

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

This is the official Hello, World example, to perform python hello.py, to open the browser to access http: // localhost: 8888 / can see the normal output server Hello, world.

A tornado web server ordinary usually consists of four components.

  1. ioloop instance, it is global tornado event loop, the engine is the core server, the example tornado.ioloop.IOLoop.current()is the default tornado ioloop instance.
  2. app instance, it represents a complete back-end app, it will mount a server socket port to provide services. Examples which may have a plurality of ioloop app instances, only one sample, in fact, may allow multiple, but a plurality of generally hardly used.
  3. handler class that represents the business logic, we conducted is to write piles of side development when the service handler to service client requests.
  4. Routing table, and it specifies the url rule handler attached to form a route map. When a request comes in, according to the access request url query route map to find the appropriate service handler.

The relationship between these four components is a ioloop contains multiple app (managing multiple service ports), a app contains a routing table, routing table contains multiple handler. ioloop is the engine core services, it is the engine, responsible for receiving and responding to client requests, responsible for driving the handler to run the business, responsible for the implementation of the internal server timed tasks .

When a request comes in, ioloop read request unpacks a http request object is to find the corresponding app on the socket routing table, the routing table by the query request url object mounted Handler, then execute handler. After execution handler method typically returns an object, ioloop responsible for packaging the object to the target sequence http response sent to the client.

With a ioloop instance is running in a single-threaded environment.

About ioloop:

tornado.ioloop - the Main Event Loop
An the I / O Event Loop for non-blocking . Sockets (nonblocking socket interface)
IOLoop The IS A warpper around ASYNCIO Event Loop (asynchronous event loop).

 

reference:

https://tornado-zh.readthedocs.io/zh/latest/guide/async.html

https://zhuanlan.zhihu.com/p/37382503

https://www.tornadoweb.org/en/stable/ioloop.html

Guess you like

Origin www.cnblogs.com/Flash-ylf/p/11618578.html