In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use Tornado in Python. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Tornado basic operation Hello World
A classic example of hello world:
Import tornado.web# view class MainHandler (tornado.web.RequestHandler): def get (self): self.write ("Hello World.") # routing application = tornado.web.Application ([(r "/", MainHandler), (r "/ hello", MainHandler),]) if _ _ name__ = ='_ main__': import tornado.ioloop application.listen (8000) tornado.ioloop.IOLoop.instance (). Start ()
The whole process is actually creating a socket server and listening on port 8000. When the request arrives, the method in the corresponding class is specified to handle the request according to the url and the request method in the request (post, get, put, etc.). In the above example, when url matches the routing system, the server returns Hello World to the browser, otherwise it returns 404: Not Found (the value defined within tornado), that is, a http request and response is completed.
Template engine
The template language in Tornao is similar to that in django. The template engine loads the template file into memory, then embeds the data in it, finally gets a complete string, and then returns the string to the requester.
But there's a difference. Tornado's templates support "control statements" and "expression statements", which are wrapped in {% and%}. For example {% if len (items) > 2%}. Expression statements are wrapped with {{and}}, such as {{items [0]}}.
The format of the control statement and the corresponding Python statement is basically the same. If, for, while and try are supported, and the logical end of these statements needs to be marked with {% end%}. Template inheritance is also implemented through extends and block statements. These are described in detail in the template module code documentation. Before using the template, you need to set the template path in setting: "template_path": "tpl"
A simple example of using a template engine, back-end code:
Import tornado.webclass IndexHandler (tornado.web.RequestHandler): def get (self): self.render ("index.html", K1 / index v1, K2) # K1 and K2 are passed to the template engine for processing application = tornado.web.Application ([(r "/ index", IndexHandler),]) if _ name__ = ='_ main__': import tornado.ioloop application.listen (8000) tornado.ioloop.IOLoop.instance (). Start ()
Front-end code, the use of template language:
Hello World {{K1}} {% if K2 = = 'v2'%} K2 = = v2 {% else%}} K2! = v2 {% end%} load configuration
The above front-end code is best stored in a directory, such as a new tpl directory to store. After moving the html file, the render () method can't find it now. Of course, you can change the parameters to add the directory name. However, the recommended practice is to add the tpl directory to the configuration, modify the above code, and add configuration information:
Class IndexHandler (tornado.web.RequestHandler): def get (self): self.render ("index.html", K1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
First prepare the following page, fill in the keyword you want to search in the input box, and then jump to the search engine search results after submission:
The code at the back end:
Import tornado.webclass SearchHandler (tornado.web.RequestHandler): def get (self): self.render ("baidu.html") def post (self): wd = self.get_argument ('wd') print (wd) self.redirect (' https://www.baidu.com/s?wd=%s'% wd) settings = {'template_path':' tpl'} application = tornado.web.Application ([(r "/ baidu") SearchHandler),], * * settings) if _ _ name__ = ='_ main__': import tornado.ioloop application.listen (8000) tornado.ioloop.IOLoop.instance () .start ()
In the above example, the post request is finally returned with redirect (), which is the jump of the page.
The methods to get the submitted parameters are as follows:
Class LoginHandler (tornado.web.RequestHandler): def post (self): # get the data transferred in the form of GET in URL self.get_query_argument () self.get_query_arguments () # get the data passed in the form of POST in the body of the request self.get_body_argument () self.get_body_arguments () # from 2 above Try to get self.get_argument () self.get_arguments () static file (picture)
Static files are downloaded directly to users, so you should store them separately and register the corresponding directory in the configuration. How to write the configuration:
Settings = {'template_path':' tpl', # template 'static_path':' imgs', # static file}
You can now create a new folder static to hold static files according to the name in the configuration. And put a picture in it.
Static is deliberately used as the name of the static file folder here, it's just a registration folder, but when referencing the front end, no matter where your static file is placed, it uses the name of the static/ file.
Add an img tag to the html and verify the effect. Notice that static is used in src, not the real name of the folder:
Here, the front end references must use static, but the name can also be customized:
Settings = {'template_path':' tpl', # template 'static_path':' imgs', # static file 'static_url_prefix':' / statics/', # Note that there should be slashes on both sides /} other operations
Self.request.cookies: get cookies
Self.set_cookie (): setting cookie
Self.request.headers: get the request header
Self.set_header (): sets the response header. If the same response header appears, it will be overridden
Self.add_header (): sets the response header, and appends it if the same response header appears
Tornado does not provide session, so if you want to use it, you have to write it separately. Similarly, there is no cache.
Advanced operation
The most basic is the above, here to add something else.
Custom UIMethod and UIModule
This is the custom function in the template engine.
What UIMethod customizes is a function, and what UIModule customizes is a class.
Define
Write custom functions and custom classes separately in the file:
# ui_methods.pydef test1 (self): # self cannot remove return "TEST1" def test2 (self): return "TEST2" # ui_module.pyfrom tornado.web import UIModulefrom tornado import escapeclass Test (UIModule): def render (self, * args, * * kwargs): return escape.xhtml_escape ('UIModule TEST')
Register
Write a complete service and add the registration code here. Import the above files first, and then register them in settings:
Import tornado.webimport ui_methods as mtimport ui_modules as mdclass MainHandler (tornado.web.RequestHandler): def get (self): self.render ('ui.html') settings = {' template_path': 'tpl', # template' static_path': 'static', # static file It doesn't matter here 'static_url_prefix':' / statics/', # notice that there should be slashes on both sides / 'ui_methods': mt,' ui_modules': md,} application = tornado.web.Application ([(r "/ ui", MainHandler),], * * settings) if _ _ name__ = ='_ main__': import tornado.ioloop application.listen (8000) tornado.ioloop.IOLoop.instance (). Start ()
Use
Here, you only need to understand the method called by the front end.
UI Method
{{test1 ()}}
{{test2 ()}}
UI Module {% module Test ()%}
The method in UIModule
The content returned by the render method is what is displayed at the location where the template is called:
Class Test (UIModule): def javascript_files (self): pass def embedded_javascript (self): pass def css_files (self): pass def embedded_css (self): pass def render (self, * args, * * kwargs): return escape.xhtml_escape ('UIModule TEST')
The javascript method inserts the script tag and the js code at the end of the body
The css method inserts the style tag into the head and sets the css
Files is to import the file directly and set it up.
Embedded is to insert the returned string as a setting
CSRF
First enable csrf in settings:
Settings = {"xsrf_cookies": True,}
Use in form
{% raw xsrf_form_html ()%}
{{xsrf_form_html ()}} can output the complete input tag, but the direct reuse is parsed into a string, and the information with the tag is displayed as a string. So the above uses {% raw xsrf_form_html ()%}.
Use in Ajax
When Ajax is used, it is essentially to get the local cookie, and then send the request with cookie:
Function getCookie (name) {var r = [xss_clean] .match ("\\ b" + name + "= ([^;] *)\\ b"); return r? R [1]: undefined;} jQuery.postJSON = function (url, args, callback) {args._xsrf = getCookie ("_ xsrf"); $.ajax ({url: url, data: $.param (args), dataType: "text", type: "POST", success: function (response) {callback (eval ("(" + response + "));});}; upload files
First prepare a html page where the form form uploads the file:
Upload files
Receive uploaded files:
Import tornado.webclass MainHandler (tornado.web.RequestHandler): def get (self): self.render ('index.html') def post (self, * args, * * kwargs): file_metas = self.request.files ["fff"] # print (file_metas) for meta in file_metas: file_name = meta [' filename'] with open (file_name 'wb') as up: up.write (meta [' body']) settings = {'template_path':' template',} application = tornado.web.Application ([(r "/ index", MainHandler),], * * settings) if _ _ name__ = ='_ main__': import tornado.ioloop application.listen (8000) tornado.ioloop.IOLoop.instance (). Start ()
Upload files can also be used Ajax, in addition, with the help of iframe tags to achieve pseudo-Ajax implementation, slightly.
Asynchronous non-blocking
Asynchronous non-blocking IO, high concurrency and high performance are the characteristics of tornado, so this section is very important. But the specific content is not understood, can only try to remember some.
First, introduce the following two modules:
From tornado import genfrom tornado.concurrent import Futureclass AsyncHandler (tornado.web.RequestHandler): @ gen.coroutine def get (self): future = Future () future.add_done_callback (self.doing) yield future def doing (self,*args, * * kwargs): self.write ('async') self.finish ()
When sending a GET request, because the method is decorated with @ gen.coroutine and yield a Future object, the Tornado waits for the user to place data or send a signal to the future object, and if the data or signal is obtained, the doing method is executed.
After the request is sent here, it will never be returned, just that Tornado has been waiting as mentioned above. Wait for the method future.set_result (result) to be called. The callback function is then called, and the parameters passed in the set_result method can be obtained through future.result (). That's roughly the way it is used, but it's a little hard to understand without an example.
Future class
The Future class is located in the concurrent module of the tornado source code. Here is a portion of the code in the Future class for analysis:
Class Future (object): def done (self): return self._done def result (self Timeout=None): self._clear_tb_log () if self._result is not None: return self._result if self._exc_info is not None: raise_exc_info (self._exc_info) self._check_done () return self._result def add_done_callback (self Fn): if self._done: fn (self) else: self._callbacks.append (fn) def set_result (self Result): self._result = result self._set_done () def _ set_done (self): self._done = True for cb in self._callbacks: try: cb (self) except Exception: app_log.exception ('exception calling callback% r for% ringing, cb Self) self._callbacks = None
Important member functions of the Future class:
Def done (self): whether the _ result member of Future is set
Def result (self, timeout=None): get the result of the Future object
Def add_done_callback (self, fn): add a callback function fn to the Future object. If the Future object is already done, execute fn directly, otherwise add fn to a member list of the Future class and save it.
Def_set_done (self): an internal function, mainly traversing the list, calling the callback function in the list one by one, which is added by the previous add_done_calback.
Def set_result (self, result): set result to the Future object and call _ set_done. That is, when the Future object gets the result, all callback functions added by add_done_callback are executed.
In the end, you want future to call set_result, and then execute the callback function.
Custom asynchronous non-blocking Web framework
The main purpose of this section is to show and analyze how tornado implements asynchronous non-blocking in the form of source code. The code should not be super source code, but just draw lessons from the idea and do a lot of simplification.
Here is the code to implement asynchronous non-blocking, mainly select+socket:
Https://www.cnblogs.com/wupeiqi/p/6536518.html
What scenarios consider using Tornado
Complex applications are still developed in django.
If you want to develop an API function, or other simple tools, applications, you don't have to manipulate the database. You can use tornado or some other simple framework. You don't need to use django.
The simple framework you can choose from is Flask.
Thank you for reading! This is the end of this article on "how to use Tornado in Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.