Overview
Tornado is an open-source version of the extensible, non-blocking Web server and its associated tools used by FriendFeed. The web framework looks somewhat like web.py or Google's webapp, but in order to make efficient use of the non-blocking server environment, the web framework also contains useful tools and optimizations that are relevant.
There is a significant difference between the Tornado and the current mainstream WEB server framework, including most Python frameworks: It's a non-blocking server and it's pretty fast. Profiting from its non-blocking approach and the use of Epoll, Tornado can handle thousands of connections per second, which means that Tornado is an ideal web framework for real-time Web services. Our main purpose in developing this WEB server is to deal with the real-time functionality of FriendFeed, where every active user maintains a server connection in the FriendFeed application. (For questions about how to scale up the server to handle the connections of thousands of clients, see c10k problem.) )
Download the installation:
| 1234 |
pip3 install tornado源码安装https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz |
Framework uses
First, get started quickly
+ View Code
Execution process:
- Step One: Execute script, listen on port 8888
- Step Two: Browser Client access/index-Http://127.0.0.1:8888/index
- Step three: The server accepts the request and processes the request by the corresponding class
- Fourth step: After the class accepts the request, it is based on the request method (Post/get/delete ... ) and execute the appropriate method
- Fifth Step: Method returns the string content of the value of the Send browser
asynchronous non-blocking example
Second, the routing system
The routing system is actually the correspondence between the URL and the class, here is different from other frameworks, many other frameworks are URL correspondence function, each URL in tornado corresponds to a class.
+ View Code
Tornado supports routing of two-level domain names, such as:
Third, template engine
The template language in Tornao is similar to Django, where the template engine loads the template file into memory and then embeds the data in it, eventually acquiring a complete string and returning the string to the requestor.
The Tornado template supports "control statements" and "expression statements", which are used {% and %} wrapped for example by control statements {% if len(items) > 2 %} . Expression statements are used {{ and }} wrapped up, for example {{ items[0] }} .
The format of the control statement and the corresponding Python statement is basically exactly the same. We support if , for while and try , where these statements logically end, they need to {% end %} be labeled. extendstemplate inheritance is also implemented through and block statements. These are template described in detail in the code documentation for the module.
Note: You need to set the template path in setting before using the template: "Template_path": "TPL"
1. Basic use
app.pyindex.htmlOther methods
2. Master version
layout.htmlindex.html
3. Import
header.htmlindex.html
4, custom Uimethod to Uimodule
A. Definition
uimethods.pyuimodules.py
B. Registration
View Code
C. Use
View Code
Iv. Static files
For static files, you can configure the directory for static files and the prefix used for the previous segment, and Tornaodo also supports static file caching.
app.pyindex.html
Note: The implementation of the static file cache
View Code
V. Cookies
Cookies can be manipulated in tornado, and cookies can also be signed to place a forgery.
1. Basic operation
View Code
2. Encrypted cookie (signature)
Cookies can easily be forged by malicious clients. To add information that you would like to have in your cookie to keep the current logged-in user's ID, you need to sign the cookie to prevent forgery. Tornado supports this function directly through the Set_secure_cookie and Get_secure_cookie methods. To use these methods, you need to provide a key when you create the app with the name Cookie_secret. You can pass it as a keyword parameter into the app's settings:
View CodeInternal Algorithms
The nature of the signature cookie is:
Write Cookie process:
- To encrypt a value base64
- Hash algorithm (cannot be parsed backwards) to sign content other than value
- Stitching Signature + Encrypted value
Read the cookie process:
- Read Signature + encrypted value
- Verifying a signature
- Base64 decrypt, Get value content
Note: Many API validation mechanisms and security cookies implement the same mechanism.
user authentication based on cookie-demoimplementation of user authentication based on signature cookie-demo
3. JavaScript Operation Cookie
Because cookies are stored on the browser side, JavaScript can also be used to manipulate cookies on the browser side.
| 123456789 |
/*设置cookie,指定秒数过期 */function setCookie(name,value,expires){ vartemp = []; varcurrent_date = newDate(); current_date.setSeconds(current_date.getSeconds() + 5); document.cookie = name + "= "+ value +";expires="+ current_date.toUTCString();} |
For parameters:
- Cookies under domain-specific domains
- The cookie in the specified URL under path domain name
- Secure HTTPS use
Note: jquery also has the specified plugin jquery cookie specifically for manipulating cookies, bash here
Liu, CSRF
Exaggerated request forgery in tornado and similar in Django, cross-site forgery requests (Cross-site request forgery)
Configurationuse-Normal formUse-AJAX
Note: When using AJAX, it is essentially going to get local cookies, carry cookies, and send requests.
Vii. Uploading Files
1, Form form upload
HTMLPython
2. Ajax uploads
html-xmlhttprequestHtml-jqueryHtml-iframePythonextension: An IFRAME-based implementation of Ajax upload exampleView Codeother
Eight, verification code
The CAPTCHA principle is that the background automatically creates a picture with random content and then outputs the content to the page via an IMG tag.
To install the image processing module:
Example:
Verification Code Demo source download: Punch here
Nine, asynchronous non-blocking
1. Basic use
Adorner + future for asynchronous non-blocking of tornado
| 1234567891011121314 |
classAsyncHandler(tornado.web.RequestHandler): @gen.coroutine defget(self): future =Future() future.add_done_callback(self.doing) yieldfuture # 或 # tornado.ioloop.IOLoop.current().add_future(future,self.doing) # yield future defdoing(self,*args, **kwargs): self.write(‘async‘) self.finish() |
When a GET request is sent, because the method is @gen.coroutine decorated and yields a future object, Tornado waits for the user to place data or send a signal to the future object, and if the data or signal is obtained, Start executing the doing method.
Asynchronous nonblocking the other requests can now be processed when the tornaod waits for the user to place data into the future object.
Note: This connection is kept open while waiting for the user to place data or signals into the future object.
2, synchronous blocking and asynchronous non-blocking contrast
Synchronous Blockingasynchronous non-blocking
3. HttpClient Class Library
Tornado provides an asynchronous non-blocking use of the HttpClient Class library for sending HTTP requests, which mate with tornado.
| 12345678910111213 |
classAsyncHandler(tornado.web.RequestHandler): @gen.coroutine defget(self): fromtornado importhttpclient http =httpclient.AsyncHTTPClient() yield http.fetch("http://www.google.com", self.endding) defendding(self, response): print(len(response.body)) self.write(‘ok‘) self.finish() |
customizing Web Components
First, Session
1. Object-Oriented Foundation
Object-oriented access to objects in an indexed manner requires an internal implementation of the __getitem__, __delitem__, __setitem__ methods
+ View Code
2. Tornado extension
In the Tornado framework, the Initialize method is executed by default before methods such as Get/post, such as handler, so you can customize the way that all requests are performed before processing ...
+ View Code
3. Session
The session is essentially a container that is defined on the server side to hold the user back, and it must rely on cookies to implement it.
Custom Session
4. Distributed session
Conformance HasiSession
Second, form verification
In web programs, it often involves a lot of work on forms validation, such as: judging if the input is empty, and whether it conforms to the rules.
HTMLPython
Because validation rules can be reused in code, they can be defined like this:
View Code
The tornado of Python-----web framework