Tronado learning, tornado

Source: Internet
Author: User

Tronado learning, tornado

Request handler and request parameters:

Original starting: http://www.cnblogs.com/zxlovenet/p/4128644.html

The program maps the URL to the subclass of tornado. web. RequestHandler.
# code 1class MainHandler(tornado.web.RequestHandler):   def get(self):       self.write("You requested the main page") class StoryHandler(tornado.web.RequestHandler):   def get(self, story_id):       self.write("You requested the story " + story_id) application = tornado.web.Application([   (r"/", MainHandler),   (r"/story/([0-9]+)", StoryHandler),])
Get_argument () method to obtain query string parameters. Self. request. files can be used to access and upload files. Use the self. request. arguments. items () method in the inheritance class to obtain all returned objects. Override the method function of RequestHandler:The program calls the initialize () function. The parameter of this function is the keyword Parameter definition in Application configuration. The initialize method generally stores the input parameters in the member variables without generating some output or calling methods such as send_error.
The program calls prepare (). No matter which HTTP method is used, prepare is called, so this method is usually defined in a base class and then reused in the subclass. Prepare can generate output information. If it calls the finish (or send_error) function, the entire processing process ends. The program calls an HTTP method, such as get (), post (), and put. If there is a group match in the regular expression mode of the URL, the related match will be passed into the method as the parameter. For details, see code 1. Some method functions in RequestHandler need to be redefined in its subclass. # Handler \ base. py get_current_user () # process to obtain the current user Redirection:Use self. redirect or RedirectHandler.
application = tornado.wsgi.WSGIApplication([   (r"/([a-z]*)", ContentHandler),   (r"/static/tornado-0.2.tar.gz", tornado.web.RedirectHandler,    dict(url="http://github.com/downloads/facebook/tornado/tornado-0.2.tar.gz")),], **settings)
  Template:The template supports {% control Statement %} and {expression} to inherit from the template through extends and block. Cookie and Cookie security:Enhance security through the following methods
class MainHandler(tornado.web.RequestHandler):   def get(self):       if not self.get_secure_cookie("mycookie"):           self.set_secure_cookie("mycookie", "myvalue")           self.write("Your cookie was not set yet!")       else:           self.write("Your cookie was set!") application = tornado.web.Application([   (r"/", MainHandler),], cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")

 

Another configuration method:
class MainHandler(BaseHandler):   @tornado.web.authenticated   def get(self):       name = tornado.escape.xhtml_escape(self.current_user)       self.write("Hello, " + name) settings = {   "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",   "login_url": "/login",}application = tornado.web.Application([   (r"/", MainHandler),   (r"/login", LoginHandler),], **settings)

 

@ Tornado. web. authenticated # cookie_secret for user authentication # cookielogin_url for encryption # record the redirection address xsrf_cookies # Switch the XSRF Protection Mechanism Static files and active File Cache: "static_path": os.path.join(os.path.dirname(__file__), "static") static_url()The function converts the relative address to /static/images/logo.png?v=aae54The v parameter is the hash value of the logo.png file. The Tornado server sends it to the browser and caches the relevant content permanently.
Because the value of v is calculated based on the file content, if you update the file or restart the server, a new value of v is obtained, in this way, the browser will request the server to obtain the new file content. If the file content does not change, the browser will always use locally cached files, which can significantly improve the page rendering speed. Localization:  UI module:
class HomeHandler(tornado.web.RequestHandler):   def get(self):       entries = self.db.query("SELECT * FROM entries ORDER BY date DESC")       self.render("home.html", entries=entries) class EntryHandler(tornado.web.RequestHandler):   def get(self, entry_id):       entry = self.db.get("SELECT * FROM entries WHERE id = %s", entry_id)       if not entry: raise tornado.web.HTTPError(404)       self.render("entry.html", entry=entry) settings = {   "ui_modules": uimodules,}application = tornado.web.Application([   (r"/", HomeHandler),   (r"/entry/([0-9]+)", EntryHandler),], **settings){% module Entry(entry, show_comments=True) %}

 

Non-blocking asynchronous requests:Tornado uses a non-blocking I/O model, so you can change this default processing behavior-keep a request in a connection state instead of returning immediately, until a primary action is returned. To implement this method, you only need to use the tornado. web. asynchronous decorator. Debugging mode and automatic overloading:If you pass debug = True to the Application constructor, the app runs in debug mode. In debugging mode, the template will not be cached, and the app will monitor modifications to the code file. If any modifications are found, the app will be reloaded. This greatly reduces the number of manual service restarts during the development process. However, some problems (such as syntax errors during import) will still bring the server offline. The current debug mode cannot avoid these problems. Http://demo.pythoner.com/itt2zh/index.html

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.