Tornado Study Notes (i)

Source: Internet
Author: User
Tags autoload

Recently began to use Tornado to do the development, the reason, mainly tornado based on Python, one code less development speed, and secondly the use of Epoll way, can carry a high volume of concurrency. In my i5 desktop with AB test, without connection to the database, the single get generated page, the approximate average concurrency of about 7900. This is much higher than PHP or Java can host concurrency. Sunline Python code maintainability is relatively much better than PHP and has a clear syntax structure. Asphyxication, Tornado frame design is very yellow and violent, with the HTTP request as the method name, usually, the user to write a page only need to have get and post two ways to define the method is enough.


In the course of learning to meet some of the more important issues, recorded later for reference, in the course of learning encountered a lot of problems, the basic is to rely on the wall to solve, Baidu is very painful. The records are more fragmented, and may not be limited to tornado, but also include some knowledge of Python. Because I am also in the process of learning, so some things may not be detailed or understand in place, Tornado Gao don't shoot.


Tornado is not very difficult to get started, as long as the understanding of the way he handled it well done. Tornado when processing a Web page, the connection to the URL is actually a route map to the class. The methods in the class are usually just two, processing the GET or post of the connection request. So tornado's page is easy to write. For example, this is a class that is used to authenticate the logged-on user, one-line explanation:

Class signinhandler (Basehandler):  #引入BaseHandler     def post (self):  # The Post method of HTTP is the corresponding         username = of the Post method in the Get rendered form.  self.get_argument (' username ')   #获取form中username的值          Password = self.get_argument (' password ')   #获取form中password的值          conn = mysqldb.connect (' localhost ', user =  ' root ',  passwd =   ', db =  ' datacenter ', charset =  ' UTF8 ', cursorclass =  MySQLdb.cursors.DictCursor)   #连接数据库, specifies that the purpose of Cursorclass is to render the returned result as a dictionary, if not written, is returned as a tuple          cursor= conn.cursor ()   #定义数据库指针          sql =  ' select * from dc_users where username=%s and  Password=password (%s) '   #写sql, why does this        cursor.execute (sql,  (Username, password,)) after the sample writing   #执行SQL         row = cursor.fetchone ()   #获取一条, The return value is dict because cursorclass = mysqldb.cursors.dictcursor is defined when the database is connected earlier, and of course you need to import mysqldb.cursors the package         if row:  #如果存在记录              self.set_secure_cookie (' id ',  STR (row[' id ')). Encode (' Unicode_escape '),   expires_days=none)   #设置安全cookie to prevent XSRF cross-domain              self.set_secure_cookie (' username ',  row[' username '].encode (' Unicode_escape '),   expires_days=none)   #same              Self.set_secure_cookie (' role ',  row[' role '].encode (' Unicode_escape '),   expires_days=none)  # Same            ip = self.request.remote_ip  #获取来访者IP              sql =  ' Update dc_users set  last_access = now (),  last_ip=%s where id = %s '   #认证审计变更的SQL              cursor.execute (sql,  (ip, row[' id ') ,))   #执行SQL             conn.commit ()  # Submit Execution             cursor.close ()   #关闭指针              conn.close ()   #关闭数据库连接              self.redirect ('/')   #转入首页              return  #返回, according to the official documentation requirements, after redirect need to write empty return, otherwise there may be problems, There are real problems with the measurements    &Nbsp;    else:  #如果不存在记录              self.redirect ('/signin ')   #跳转回登录页面              return    def get (self):  #HTTP  get Way          self.render (' users/login_form.html ')   #渲染登录框HTML


Login_form.html content is as follows

{% include  ' header.html '  %} <!--introduce header file, need to follow login_form under the same path, otherwise write relative path, such as  {%  include  '. /header.html '  %} --><div class= "container" >    


For the main code, the following should be:

#-*- coding: utf-8 -*-import sysreload (SYS) sys.setdefaultencoding (' Utf-8 ') import  tornado.ioloopimport tornado.webimport tornado.httpserverimport tornado.autoreloadimport  Osclass basehandler (Tornado.web.RequestHandler):     def get_current_user (self):         user = self.get_secure_cookie (' username ')          return userclass indexhandler (BaseHandler):      @tornado. Web.authenticated    def get (self):         if not self.current_user:             self.redirect ('/signin ')   #如未登录, the Get method of jump Signin,signin is called login_form.html page              return         self.render (' Welcome.hTml ')   #否则渲染welcome .htmlsettings =     {          "Cookie_secret":  "Heavymetalwillneverdie",  #Cookie  secret          "Xsrf_cookies": true,  #开启跨域安全           "gzip": false,  #关闭gzip输出          "Debug":  false,   #关闭调试模式, in fact debugging mode is very tangled matter, I like to open.          "Template_path":  os.path.join (Os.path.dirname (__file__),   "./templates"),  #定义模板, i.e. login_form.html or header.html relative to the location of the program           "Static_path":  os.path.join (Os.path.dirname (__file__),  "./static"),  #定义JS,  CSS and other files relative to the location of the program          "Login_url":  "/signin",  #登录URL为/ Signin    }application = tornado.web.application ([     (r "/",  indexhandler),  #路由设置/  use indexhandler     (r "/signin",  Signinhandler)  # signin using signinhandler], **settings) if __name__ ==  "__main__":   #启动tornado, in the configuration if debug is turned on, you can use AutoLoad, belong to development mode, if you turn off debug, you can not use AutoLoad, belong to production mode. The implication of AutoLoad is that when Tornado detects any file changes, it does not need to restart the server to see the corresponding page changes, otherwise it is modified to see changes.     server = tornado.httpserver.httpserver (application)      Server.bind (10002)     server.start (0)      Tornado.ioloop.IOLoop.instance (). Start ()


For the SQL section, execution is best written as Cursor.execute (SQL, (ID)), and the object of%s is passed to the Execute method in tuples, which is designed to minimize the occurrence of SQL injection. If you write directly as ' select * ' from XXX where id = ' + id ' or ' select * from xxx where id =%s '% ID, it will be injected. In addition, if it is sqlite3, you need to write ' select * from xxx where id=? ', then execute the same way.


In addition, if the Prohibit XSRF cross-domain function is turned on, the {% Module xsrf_form_html ()%} must be added to each HTML form form, otherwise a forbidden error will occur.


The next article records the encoding format processing, which is most annoying on python2.


This article from "Practice Test Truth" blog, declined reprint!

Tornado Study Notes (i)

Related Article

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.