Ten minutes to learn web development tool tornado

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/xufive/article/details/96281879

1 Introduction

一身转战三千里,一剑曾当百万师。
今日赠君tornado,长风破浪会有时。

python's, gathering together, Hero and play. Alone for web development, there webpy, web2py, bottle, pyramid |, zope2, flask, tornado, django and so forth. More popular in recent years, probably it is the flask, tornado and a django.

Comparing the performance of each of the above web development framework, a search online, overwhelming - this is not the focus of this discussion, but one thing I would like to remind you: in many modules above, only the tornado along with asynchronous IO, webserver, web FRAMEWORK major functions, but it is also the most simple, learning the minimum threshold. There python language-based programmer, only takes ten minutes to the sexually explicit.

For the tornado, I have deep feelings. If the web development framework compared to the cold weapons in the hands of programmers, I think the flask is like a spear, ethereal and elegant, dazzling dance; django like euphorbia, combined spear Ge as a whole, piercing, can Sideswipe, matchless; tornado and benefits in the show outside, like a sword. Sword has a high status in Chinese traditional martial arts, weapons of God, are thought to have a gentleman of the wind.

2. From hello, world begin

Closer to home. If your python environment tornado has not installed, please use pip install:

pip install tornado

The following code, although only a mere six lines (not including the two rows of imported modules), but it is a complete web service program. Run the following code, it opens up a web service, accessible directly from the native browser http://127.0.0.1 , no accident, then, our first web page hello, world can be displayed properly.

demo.py

# -*- coding: utf-8 -*-

import tornado.ioloop 
import tornado.web

class HomeHandler(tornado.web.RequestHandler): 
    def get(self): # 响应以get方式发送的请求
        self.write("hello, world") # 向请求者(浏览器)应答hello, world

app = tornado.web.Application([ (r"/", HomeHandler), ]) # URL映射
app.listen(80) # 绑定侦听端口
tornado.ioloop.IOLoop.instance().start() # 启动服务

If you know how much a little http protocol, know get / post method, I believe you will be able to read. Maybe your project planning and a lot of url, maybe you need to listen for non-service port 80, it does not matter, expand on the line in this code. Only six lines! ! ! Please let us into sharp, concise, to pay tribute to the all-powerful python!

Draw focus:tornado.web.RequestHandler.write () can not only accepts a string argument, you can also accept a list or dictionary parameters - if the type of response to json, this reload feature is very efficient

3. The most simple login

Suppose we have such a web service needs:

  1. Home: address "/" display "Click here to sign in" two Chinese characters, click the jump to the login page
  2. Login Page: address "/ login", in order to get access, the account number, login and password input box button; access to post, submit the form is submitted, validate the login information. Successful login, jump to the personal information page, otherwise, go to Home
  3. Personal Information Page: address "/ me", displays the login account

With the code above is based on our first work to be done is an association between the URL and the corresponding processing class. This work is actually very easy and pleasant:

app = tornado.web.Application([
	(r"/", HomeHandler), 
	(r"/login", LoginHandler), 
	(r"/me", MeHandler)
])

Next, we want to achieve HomeHandler, LoginHandler and MeHandler the three classes. Usually, we are accustomed to deal with these categories and corresponding URL, save it as a separate file, such as a file named handlers.py , then the server script demo.py import them.

handlers.py

# -*- coding: utf-8 -*-

import tornado.web

class HomeHandler(tornado.web.RequestHandler): 
    """响应主页请求"""
    
    def get(self): # 以get方式请求
        self.write("""<!DOCTYPE html><html><body><a href="login">点此登录</a></body></html>""")

class LoginHandler(tornado.web.RequestHandler): 
    """响应登录页请求"""
    
    def get(self): # 以get方式请求
        self.write(
            """
            <!DOCTYPE html><html><body><form method="POST" action="/login">
                账号:<input type="text" name="account" value="" /><br />
                密码:<input type="password" name="passwd" value="" />
                <input type="submit" value="确定" />
            </form></body></html>
            """
        )
    
    def post(self): # 以post方式请求(本例为提交表单)
        account = self.get_argument('account', None)
        passwd = self.get_argument('passwd', None)
        
        if account == 'xufive' and passwd == 'dgdgwstd':
            self.redirect('/me?name=%s'%account)
        else:
            self.redirect('/')

class MeHandler(tornado.web.RequestHandler): 
    """响应个人信息页请求"""
    
    def get(self): # 以get方式请求
        name = self.get_argument('name', None)
        if name:
            self.write(
                """
                <!DOCTYPE html><html><head><meta charset="UTF-8" /></head>
                <body>欢迎你来到这里,%s</body></html>
                """%name
            )
        else:
            self.redirect('/')

Accordingly, the service becomes a script like this:

demo.py

# -*- coding: utf-8 -*-

import os
import tornado.ioloop 
import tornado.web
from tornado.options import parse_command_line

from handlers import *

parse_command_line()
app = tornado.web.Application(
    handlers=[
        (r"/", HomeHandler), 
        (r"/login", LoginHandler), 
        (r"/me", MeHandler)
    ],
    template_path = os.path.join(os.path.dirname(__file__), 'templates')
)
app.listen(80) # 绑定侦听端口
tornado.ioloop.IOLoop.instance().start() # 启动服务

Draw focus:tornado.web.RequestHandler.get_argument () can be read through the form and parameters passed QueryString

4. template technology

Read this far, you must be wondering: Why server program which mixed a lot of html code? Do not worry, the above code is just to help you build the basic concept, in fact, tornado was one of the few support frame template technology is in place, the technology not only supports template inheritance, child support templates. Let us step by step on how to use the template.

Step 1: templates stored?

In the server-side script, when we use tornado.web.Application () to create an application, you typically pass a template_path parameter, this parameter is the path to save the template file. The above example has increased this parameter, we just put in the template file and demo.py at the same level templates folder on it.

Step 2: How to write a template?

In fact, the template is the html file, just mix a small amount of sign special agreement. A web project, usually by a number of pages, the pages have a lot in common, so a base class template is necessary.

base.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <!-- 此处省略各种样式表文件 -->
  </head>
  <body>
  {% block block_body %}{% end %}
  </body>
<html>

Base.html base class template defines a block_body container, if necessary, we define more containers anywhere in the base class templates. Suppose that we need a personal page template, can be inherited base.html directly, and then only to fill in this part block_body on the line.

me.html

{% extends "base.html" %}
{% block block_body %}
<h1>欢迎你来到这里,{{name}}</h1>
{% end %}

Personal information page template primer, we use {{}} references a variable name

Step 3: How to use a template?

Very simple, we use the front tornado.web.RequestHandler.write () response message to the browser, is now using this template:

class MeHandler(tornado.web.RequestHandler): 
    """响应个人信息页请求"""
    
    def get(self): # 以get方式请求
        name = self.get_argument('name', None)
        if name:
            self.render('me.html', name=name )
        else:
            self.redirect('/')

Common template syntax is summarized below

  1. Reference variables: {{...}}
  2. Reference python expression: {% ...%}
  3. Cycle:% for { var in expr %} {% ...%} End
  4. 分支:{% if condition %}…{% elif condition %}…{% else %}…{% end %}
  5. Reference native expression: {RAW% expr %}

5. Cookie drills

tornado.web.RequestHandler the cookie operation is very flexible, following handler shows the basic reading and writing method cookie:

class CookieHandler(tornado.web.RequestHandler): 
    def get(self): 
        visit_num = self.get_cookie('visit_num')
        if not visit_num:
            visit_num = '0'
        visit_num = str(int(visit_num)+1)
        #self.set_cookie('visit_num', visit_num, expires=None) # 内存cookie
        self.set_cookie('visit_num', visit_num, expires=time.time()+1000) # 持久化的cookie
        self.write("这是您第%s次访问本页面"%visit_num) 

If we want to use persistent Cookie (hard Cookie), in order to prevent cracking, generally to be encrypted, then in tornado.web.Application we need to set cookie_secret items (encrypted factor).

Defined tornado.web.Application, this is one of my most frequently used modes:

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", WelcomeHandler),                # 欢迎信息
            (r"/server_time",ServerTimeHandler)    # 显示服务器时间
        ]

        settings = dict(
            title = u"网站名称",
            template_path = os.path.join(os.path.dirname(__file__), 'templates'),
            static_path = os.path.join(os.path.dirname(__file__), 'static'),
            cookie_secret = 'rewqr4gfd654fdsg@$%34dfs',
            session_expiry = 0,
            login_url = "/",
            debug = 1
        )
        
        tornado.web.Application.__init__(self, handlers, **settings)

6. Session Extended

To increase tornado session mechanism, the basic idea is to derive a new class from tornado.web.RequestHandler, rewrite the initialize () method. After the instance is created when the class constructor, which will first run. We define the initialize () method reads the cookie called session_id, if there is, then read to the session name session_id file, obtain the content session, otherwise, session is empty. For details, see my book "to install tornado session wheels" , not repeat them here.

7. Postscript

This article describes how only superficially into the world of the tornado, and project information from ppt combat my lectures. Because written hastily, without considering the version compatibility, it is inevitable that errors or omissions, like him to forgive. As popular frameworks, tornado also supports almost all of the Asynchronous Client and web Socket and other web technologies, in order to master it, it needs a good read document.

Guess you like

Origin blog.csdn.net/xufive/article/details/96281879