Python's Tornado framework Asynchronous programming example _python

Source: Internet
Author: User

Tornado

Tornado is a non-blocking extensible Web server and Python Web framework written using Python, You can use Tornado to write web programs without relying on any Web server to provide efficient Web services directly. So tornado is more than just a web framework and an efficient Web server that can be used in a production environment.

Torando uses efficient asynchronous I/O models Epoll and Kqueue on Linux and FreeBSD to implement efficient Web servers, so tornado can achieve the highest performance on Linux and FreeBSD series
Interface

Of course, we can not only think of tornado as a web framework and Web server, we can use the interface provided by Tornado for efficient network asynchronous programming,

The Tornado.ioloop.IOLoop provides three interfaces that can be used for network programming:

Add_handler

def add_handler (self, FD, Handler, events):
  SELF._HANDLERS[FD] = stack_context.wrap (handler)
  Self._impl.register (FD, Events | self. ERROR)

Add_handler is used to add a socket to the main loop, accepting three parameters: FD is the file descriptor for the socket handler is the callback function that handles this socket * Events are the event registered by this socket

Update_handler

def update_handler (self, FD, events):
  self._impl.modify (FD, Events | self. ERROR)

Update_handler is used to update the existing socket response event in the live loop, accepting two parameters: FD is the file descriptor for the socket The events are new registered

Remove_handler

def remove_handler (self, FD):
  Self._handlers.pop (FD, none)
  Self._events.pop (FD, none)
  Try:
    self._impl.unregister (FD)
  except Exception:
    gen_log.debug ("Error deleting FD from Ioloop", exc _info=true)

Remove_handler for removing existing sockets in the main loop
Events

Tornado.ioloop.IOLoop provides 4 response events at the same time:

Instance

Based on the above interfaces and events, we can write a simple echo server

#!/usr/bin/env python #-*-coding:utf-8-*-# author:cold # e-mail:wh_linux@126.com # DATE:13/04/15 15:08 : Wuyi # Desc:tornado Echo Server # home:http://www.linuxzen.com # import Queue import socket from Functools Impor T partial from Tornado.ioloop import Ioloop sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) sock.setblocking (0) # Set the socket to non-blocking server_address = ("localhost", 10000) Sock.bind (server_address) s  Ock.listen (5) Fd_map = {} # file descriptor to the mapping of the socket message_queue_map = {} # socket to message queue mapping FD = Sock.fileno () FD_MAP[FD] = Sock Ioloop = ioloop.instance () def handle_client (CLI_ADDR, FD, event): s = fd_map[fd] If event & Ioloop.read : data = S.RECV (1024) if Data:print "received '%s ' from%s '% (data, CLI_ADDR) # received message Change event as write, used to send  Data to the End-to-end Ioloop.update_handler (FD, ioloop.write) message_queue_map[s].put else:print "closing %s '% cli_addr Ioloop.remove_handler (FD) s.Close () del Message_queue_map[s] if event & IOLoop.WRITE:try:next_msg = message_queue_map[s].get_
    NoWait () except Queue.Empty:print "%s Queue Empty"% cli_addr ioloop.update_handler (FD, Ioloop.read) Else:print ' sending '%s ' to%s '% (next_msg, cli_addr) s.send (next_msg) if event & Ioloop.error:p Rint "exception on%s"% cli_addr Ioloop.remove_handler (FD) s.close () del Message_queue_map[s] def handle_s Erver (FD, event): s = fd_map[fd] If event & IOLoop.READ:conn, cli_addr = s.accept () print "Connection %s "% cli_addr[0] conn.setblocking (0) conn_fd = Conn.fileno () FD_MAP[CONN_FD] = conn Handle = partial (hand Le_client, Cli_addr[0]) # joins the connection and handle registration as read events as the first parameter # join Tornado Ioloop Ioloop.add_handler (CONN_FD, Handl E, ioloop.read) message_queue_map[conn] = Queue.queue () # Create corresponding message queue Ioloop.add_handler (FD, Handle_server, IOLoop.RE

 AD) Ioloop.start ()

The code above establishes a non-blocking, efficient, asynchronous echo server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.