Python Tornado framework asynchronous programming entry example

Source: Internet
Author: User
This article mainly introduces the example of the Tornado framework asynchronous programming in Python. the idea of asynchronous programming is somewhat different from that of normal programming. For more information, see Tornado

Tornado is a non-blocking and scalable web server and Python Web framework written in Python. you can use Tornado to write Web programs without relying on any web server to directly provide efficient web services. therefore, Tornado is not only a web framework, but also an efficient web server that can be used in the production environment.

Torando uses efficient asynchronous I/O models epoll and kqueue on Linux and FreeBSD to implement efficient web servers. Therefore, tornado and FreeBSD series have the highest performance in Linux.
Interface

Of course, we can not only regard Tornado as a web framework and web server, but also use the interfaces provided by Tornado for Efficient Asynchronous network programming,

Tornado. ioloop. IOLoop provides three interfaces for network programming:

add_handlerdef 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. it accepts three parameters: fd is the socket file descriptor. handler is the callback function for processing this socket * events is the socket registration event.

update_handlerdef update_handler(self, fd, events):  self._impl.modify(fd, events | self.ERROR)

Update_handler is used to update the existing socket response events in the loop. it accepts two parameters: fd is the file descriptor corresponding to the socket. events is registered.Event

remove_handlerdef 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 is used to remove the existing socket in the main loop.
Event

Tornado. ioloop. IOLoop also provides four types of response events:

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:51 # Desc: tornado Echo Server # HOME: http://www.linuxzen.com#import Queueimport socketfrom functools import partialfrom tornado. ioloop import IOLoopsock = 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) sock. listen (5) fd_map ={}# file descriptor to socket messing message_queue_map ={}# socket to message queue fd ing fd = sock. fileno () fd_map [fd] = sockioloop = 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) # When a message is received, change the event to write, used to send data to the peer ioloop. update_handler (fd, IOLoop. WRITE) message_queue_map [s]. put (data) 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 () Queue T 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: print "exception on % s" % cli_addr ioloop. remove_handler (fd) s. close () del message_queue_map [s] def handle_server (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 (handle_client, cli_addr [0]) # use cli_addr as the first parameter # add the connection and handle registration as a read event to tornado ioloop. add_handler (conn_fd, handle, IOLoop. READ) message_queue_map [conn] = Queue. queue () # create the corresponding message Queue ioloop. add_handler (fd, handle_server, IOLoop. READ) ioloop. start ()

The above code creates a non-blocking and 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.