Web框架之tornado


Tornado Web框架

Tornado 是 FriendFeed 使用的可扩展的非阻塞式 web 服务器及其相关工具的开源版本。这个 Web 框架看起来有些像web.py 或者 Google 的 webapp,不过为了能有效利用非阻塞式服务器环境,这个 Web 框架还包含了一些相关的有用工具 和优化。

Tornado 和现在的主流 Web 服务器框架(包括大多数 Python 的框架)有着明显的区别:它是非阻塞式服务器,而且速度相当快。得利于其 非阻塞的方式和对 epoll 的运用,Tornado 每秒可以处理数以千计的连接,这意味着对于实时 Web 服务来说,Tornado 是一个理想的 Web 框架。我们开发这个 Web 服务器的主要目的就是为了处理 FriendFeed 的实时功能 ——在 FriendFeed 的应用里每一个活动用户都会保持着一个服务器连接。(关于如何扩容 服务器,以处理数以千计的客户端的连接的问题,请参阅 C10K problem。)

安装:

pip3 install tornado
 
源码安装
https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz

框架使用

快速启动一个web

import tornado.ioloop
import tornado.web
   
   
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
   
application = tornado.web.Application([
    (r"/index", MainHandler),
])
   
   
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

 

说明:

  • 第一步:执行脚本,监听 8888 端口
  • 第二步:浏览器客户端访问 /index --> http://127.0.0.1:8888/index
  • 第三步:服务器接受请求,application 根据请求的url交由对应的类处理该请求
  • 第四步:类接受到请求之后,根据请求方式(post / get / delete ...)的不同调用并执行相应的方法
  • 第五步:write方法返回值的字符串内容发送浏览器

tornado自定义settings

从上面快速启动例子发现,可以使用一个py脚本即可启动web服务,但如果涉及到html、js、css等文件,全部放到一块,显得非常杂乱,我们可以参考django的目录结构进行配置tornado

我们可以定一个配置字典,命名为settings,然后将相关配置放到字典中,最后应用到tornado即可
例子:

import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        #self.write("Hello, world")
        self.render('index.html')  #使用render 返回一个html
#自定义settings
settings = {
    "template_path":"templates",
    "static_path":"statics",
}
application = tornado.web.Application([
    (r"/index", MainHandler),
],**settings)               #应用到tornado中


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

 

tornado的路由系统

路由系统其实就是 url 和 类 的对应关系,这里不同于其他框架,其他很多框架均是 url 对应 函数,Tornado中每个url对应的是一个类。

简单多条路由

简单多条路由实现,其实就是在tornado.web.Application对象中传递多个url和对应的类即可
如下,在原来的基础上,增加一条/cmdb 的url

import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        #self.write("Hello, world")
        self.render('index.html')

class CMDBHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('CMDB')
settings = {
    "template_path":"templates",
    "static_path":"statics",
    'static_url_prefix': '/static/',
}
application = tornado.web.Application([
    (r"/index", MainHandler),
    (r"/cmdb", CMDBHandler),
],**settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

 

原生支持二级域名

tornado 还可以支持自动将主域名的子目录转换为二级域名,如 www.fuzengjie.cn/cmdb --> cmdb.fuzengjie.cn

import tornado.ioloop
import tornado.web



class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('hello word')

class CmdbHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('Cmdb')
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')
settings = {
        'template_path' :'templates',
        }

application = tornado.web.Application([
    (r'/main',MainHandler),
    (r'/index',IndexHandler),
    ],**settings)

#添加二级域名对应的url
application.add_handlers('cmdb.fuzengjie.cn',[
    (r'/main',CmdbHandler)
    ])


if __name__ == '__main__':
    application.listen(8000)
    tornado.ioloop.IOLoop.instance().start()

 

动态路由

tornado同样支持动态路由,即通过正则匹配URL,然后传参到对应的类中

import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self,user,pwd):
        self.write("Hello,%s, is %s" %(user,pwd))

class CMDBHandler(tornado.web.RequestHandler):
    def get(self,num):
        self.write('CMDB is %s' %num)
settings = {
    "template_path":"templates",
    "static_path":"statics",
    'static_url_prefix': '/static/',
}
application = tornado.web.Application([
    (r"/index/(?P<user>.*)/(?P<pwd>.*)", MainHandler),
    (r"/cmdb/(\w+)", CMDBHandler),
],**settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

 

原生支持restful api

所谓的restful api就是使用同一个api,根据请求的方式不同,来实现不同的api功能,即

  • 每一个URI代表一种资源;
  • 客户端和服务器之间,传递这种资源的某种表现层;
  • 客户端通过四个HTTP动词(get、post、delete、put),对服务器端资源进行操作,实现"表现层状态转化;

由于tornado 默认就是根据请求的方式来调用对应的方法,如用户是get请求,handler会自动执行类中get的方法,用户是post请求,会自动执行类中的post方法。所以tornado原生就支持restful api

模版语言

Tornao中的模板语言和django中类似,模板引擎将模板文件载入内存,然后将数据嵌入其中,最终获取到一个完整的字符串,再将字符串返回给请求者。

Tornado 的模板支持“控制语句”和“表达语句”,控制语句是使用 {% 和 %} 包起来的 例如 {% if len(items) > 2 %}。表达语句是使用 {{ 和 }} 包起来的,例如 {{ items[0] }}。

控制语句和对应的 Python 语句的格式基本完全相同。我们支持 if、for、while 和 try,这些语句逻辑结束的位置需要用 {% end %} 做标记。还通过 extends 和 block 语句实现了模板继承。这些在 template 模块 的代码文档中有着详细的描述。

注:在使用模板前需要在setting中设置模板路径:"template_path" : "tpl"
tornado的模版语言和python的语法差不多

基本使用

  • python代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
  
import tornado.ioloop
import tornado.web
  
  
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html", list_info = [11,22,33])
  
application = tornado.web.Application([
    (r"/index", MainHandler),
])
  
  
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

 



app.py
  • html
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>付增杰</title>
    <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
</head>
<body>

    <div>
        <ul>
            {% for item in list_info %} 
                <li>{{item}}</li>
            {% end %}
        </ul>
    </div>
    
    <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
    
</body>
</html>

 


  • 其他方法
在模板中默认提供了一些函数、字段、类以供模板使用:
escape: tornado.escape.xhtml_escape 的別名
xhtml_escape: tornado.escape.xhtml_escape 的別名
url_escape: tornado.escape.url_escape 的別名
json_encode: tornado.escape.json_encode 的別名
squeeze: tornado.escape.squeeze 的別名
linkify: tornado.escape.linkify 的別名
datetime: Python 的 datetime 模组
handler: 当前的 RequestHandler 对象
request: handler.request 的別名
current_user: handler.current_user 的別名
locale: handler.locale 的別名
_: handler.locale.translate 的別名
static_url: for handler.static_url 的別名
xsrf_form_html: handler.xsrf_form_html 的別名

 

模版和引入

tornado同样支持模版,即定义好一个模板,在其他页面直接可以应用

  • 模板

layout.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>老男孩</title>
    <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
    {% block CSS %}{% end %}
</head>
<body>

    <div class="pg-header">

    </div>
    
    {% block RenderBody %}{% end %}
   
    <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
    
    {% block JavaScript %}{% end %}
</body>
</html>

 

  • 引入
{% extends 'layout.html'%}
{% block CSS %}
    <link href="{{static_url("css/index.css")}}" rel="stylesheet" />
{% end %}

{% block RenderBody %}
    <h1>Index</h1>

    <ul>
    {%  for item in li %}
        <li>{{item}}</li>
    {% end %}
    </ul>

{% end %}

{% block JavaScript %}
    
{% end %}

 

导入

tornado 也可以导入其他html文件

  • header.html
<div>
    <ul>
        <li>1024</li>
        <li>42区</li>
    </ul>
</div>

 

  • index
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>老男孩</title>
    <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
</head>
<body>

    <div class="pg-header">
        {% include 'header.html' %}
    </div>    
</body>
</html>

 

UIMothed 和UIModule

  • UIMothed 和python的simple_tag类似,用于在渲染template的时候自定义方法
  • UIModule 用于在渲染template时,生成template中的的一些元素

使用

  • 创建uimothed和uimodule:

    uimothed和uimodule自定义方法其实就是python的函数和类。注意:自定义uimothed是在脚本中直接定义的函数(方法)即可,自定义uimodule是在脚本中定义的类

uimothed: xo.py

def test_uimothed(self,arg):      #注意,定义方法的时候需要加self
    return 'test_' + arg

 

uimodule: ox.py

from tornado.web import UIModule
from tornado import escape

class custom(UIModule):

    def render(self, *args, **kwargs):
        return escape.xhtml_escape('<h1>uimodule test</h1>')

 

  • 注册 先导入刚才定义的脚本,然后在settings中加载
#!/usr/bin/env python
import tornado.ioloop
import tornado.web

import xo
import ox
class MainHandler(tornado.web.RequestHandler):
    def get(self,user,pwd):
        self.write("Hello,%s, is %s" %(user,pwd))

class CMDBHandler(tornado.web.RequestHandler):
    def get(self,num):
        self.write('CMDB is %s' %num)
class TestHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')
settings = {
    "template_path":"templates",
    "static_path":"statics",
        "ui_methods":xo,
        "ui_modules":ox,
}
application = tornado.web.Application([
    (r"/index/(?P<user>.*)/(?P<pwd>.*)", MainHandler),
    (r"/cmdb/(\w+)", CMDBHandler),
    (r"/test",TestHandler),
],**settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

 

  • 使用

注意uimothed 直接使用{% uimothed%}进行调用,uimodule使用{ module uimodule}调用

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link src="/statics/index.css">
</head>
<body>
    <h1>index</h1>
    <p class=test>index for test</p>
     {% module custom(123) %}
         {{ test_uimothed('ui_mothed') }}  //注意由于tornado的模版语言遵循python语法,所以传参数的时候字符串需要加引号,否则会当变量处理
</body>
</html>

 

  • UIModule补充

    UIModule 自定义类中支持的方法

    • render:返回字符串
    • javascript_files 在前端生成 块
    • embedded_javascript 在前端生成js的代码
    • css_files 在前端生成块
    • embedded_css 在前端生成css的代码

Cookie

Tornado中可以对cookie进行操作,并且还可以对cookie进行签名以放置伪造。

  • 基本操作
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_cookie("mycookie"):
            self.set_cookie("mycookie", "myvalue")
            self.write("Your cookie was not set yet!")
        else:
            self.write("Your cookie was set!")

 

  • 加密cookie

Cookie 很容易被恶意的客户端伪造。加入你想在 cookie 中保存当前登陆用户的 id 之类的信息,你需要对 cookie 作签名以防止伪造。Tornado 通过 set_secure_cookie 和 get_secure_cookie 方法直接支持了这种功能。 要使用这些方法,你需要在创建应用时提供一个密钥,名字为 cookie_secret。 你可以把它作为一个关键词参数传入应用的设置中

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=")

 

  • 加密cookie 内部加密解密
def _create_signature_v1(secret, *parts):
    hash = hmac.new(utf8(secret), digestmod=hashlib.sha1)
    for part in parts:
        hash.update(utf8(part))
    return utf8(hash.hexdigest())

# 加密
def _create_signature_v2(secret, s):
    hash = hmac.new(utf8(secret), digestmod=hashlib.sha256)
    hash.update(utf8(s))
    return utf8(hash.hexdigest())

def create_signed_value(secret, name, value, version=None, clock=None,
                        key_version=None):
    if version is None:
        version = DEFAULT_SIGNED_VALUE_VERSION
    if clock is None:
        clock = time.time

    timestamp = utf8(str(int(clock())))
    value = base64.b64encode(utf8(value))
    if version == 1:
        signature = _create_signature_v1(secret, name, value, timestamp)
        value = b"|".join([value, timestamp, signature])
        return value
    elif version == 2:
        # The v2 format consists of a version number and a series of
        # length-prefixed fields "%d:%s", the last of which is a
        # signature, all separated by pipes.  All numbers are in
        # decimal format with no leading zeros.  The signature is an
        # HMAC-SHA256 of the whole string up to that point, including
        # the final pipe.
        #
        # The fields are:
        # - format version (i.e. 2; no length prefix)
        # - key version (integer, default is 0)
        # - timestamp (integer seconds since epoch)
        # - name (not encoded; assumed to be ~alphanumeric)
        # - value (base64-encoded)
        # - signature (hex-encoded; no length prefix)
        def format_field(s):
            return utf8("%d:" % len(s)) + utf8(s)
        to_sign = b"|".join([
            b"2",
            format_field(str(key_version or 0)),
            format_field(timestamp),
            format_field(name),
            format_field(value),
            b''])

        if isinstance(secret, dict):
            assert key_version is not None, 'Key version must be set when sign key dict is used'
            assert version >= 2, 'Version must be at least 2 for key version support'
            secret = secret[key_version]

        signature = _create_signature_v2(secret, to_sign)
        return to_sign + signature
    else:
        raise ValueError("Unsupported version %d" % version)

# 解密
def _decode_signed_value_v1(secret, name, value, max_age_days, clock):
    parts = utf8(value).split(b"|")
    if len(parts) != 3:
        return None
    signature = _create_signature_v1(secret, name, parts[0], parts[1])
    if not _time_independent_equals(parts[2], signature):
        gen_log.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < clock() - max_age_days * 86400:
        gen_log.warning("Expired cookie %r", value)
        return None
    if timestamp > clock() + 31 * 86400:
        # _cookie_signature does not hash a delimiter between the
        # parts of the cookie, so an attacker could transfer trailing
        # digits from the payload to the timestamp without altering the
        # signature.  For backwards compatibility, sanity-check timestamp
        # here instead of modifying _cookie_signature.
        gen_log.warning("Cookie timestamp in future; possible tampering %r",
                        value)
        return None
    if parts[1].startswith(b"0"):
        gen_log.warning("Tampered cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0])
    except Exception:
        return None


def _decode_fields_v2(value):
    def _consume_field(s):
        length, _, rest = s.partition(b':')
        n = int(length)
        field_value = rest[:n]
        # In python 3, indexing bytes returns small integers; we must
        # use a slice to get a byte string as in python 2.
        if rest[n:n + 1] != b'|':
            raise ValueError("malformed v2 signed value field")
        rest = rest[n + 1:]
        return field_value, rest

    rest = value[2:]  # remove version number
    key_version, rest = _consume_field(rest)
    timestamp, rest = _consume_field(rest)
    name_field, rest = _consume_field(rest)
    value_field, passed_sig = _consume_field(rest)
    return int(key_version), timestamp, name_field, value_field, passed_sig


def _decode_signed_value_v2(secret, name, value, max_age_days, clock):
    try:
        key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value)
    except ValueError:
        return None
    signed_string = value[:-len(passed_sig)]

    if isinstance(secret, dict):
        try:
            secret = secret[key_version]
        except KeyError:
            return None

    expected_sig = _create_signature_v2(secret, signed_string)
    if not _time_independent_equals(passed_sig, expected_sig):
        return None
    if name_field != utf8(name):
        return None
    timestamp = int(timestamp)
    if timestamp < clock() - max_age_days * 86400:
        # The signature has expired.
        return None
    try:
        return base64.b64decode(value_field)
    except Exception:
        return None


def get_signature_key_version(value):
    value = utf8(value)
    version = _get_version(value)
    if version < 2:
        return None
    try:
        key_version, _, _, _, _ = _decode_fields_v2(value)
    except ValueError:
        return None

    return key_version

 

  • 实现原理
    • 写cookie过程:
      • 将值进行base64加密
      • 对除值以外的内容进行签名,哈希算法(无法逆向解析)
      • 拼接 签名 + 加密值
    • 读cookie过程:
      • 读取 签名 + 加密值
      • 对签名进行验证
      • base64解密,获取值内容

CSRF

tornado 同样支持CSRF,和django类似

  • 配置

只需要在settings中开启csrf

settings = {
    "xsrf_cookies": True,
}
application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/login", LoginHandler),
], **settings)

 

  • 使用普通表单
<form action="/new_message" method="post">
  {{ xsrf_form_html() }}        //在这里会自动生成xsrf的密钥
  <input type="text" name="message"/>
  <input type="submit" value="Post"/>
</form>

 

  • 使用ajax
function getCookie(name) {
    var r = document.cookie.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 + ")"));
    }});
};

 



使用 - AJAX

注:Ajax使用时,本质上就是去获取本地的cookie,携带cookie再来发送请求

异步

tornado 默认是单进程单线程的,当第一个请求还没处理完,第二个请求会等待第一个请求完成,而tornado的异步实现了单进程单线程处理多并发的请求,其内部原理就是使用的协程

装饰器 + Future 从而实现Tornado的异步非阻塞

class AsyncHandler(tornado.web.RequestHandler):
 
    @gen.coroutine
    def get(self):
        future = Future()
        future.add_done_callback(self.doing)
        yield future
        #
        # tornado.ioloop.IOLoop.current().add_future(future,self.doing)
        # yield future
 
    def doing(self,*args, **kwargs):
        self.write('async')
        self.finish()

 

当发送GET请求时,由于方法被@gen.coroutine装饰且yield 一个 Future对象,那么Tornado会等待,等待用户向future对象中放置数据或者发送信号,如果获取到数据或信号之后,就开始执行doing方法。

异步非阻塞体现在当在Tornaod等待用户向future对象中放置数据时,还可以处理其他请求。

注意:在等待用户向future对象中放置数据或信号时,此连接是不断开的。

  • httpclient类库

Tornado提供了httpclient类库用于发送Http请求,其配合Tornado的异步非阻塞使用。

class AsyncHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        from tornado import httpclient
 
        http = httpclient.AsyncHTTPClient()
        yield http.fetch("http://www.google.com", self.endding)
 
 
    def endding(self, response):
        print(len(response.body))
        self.write('ok')
        self.finish()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM