Python(九)Tornado web 框架

一、简介

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

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

  请参见 Tornado 文档 或 Tornado 原文文档 (镜像)以详细了解该 Web 框架。

下载和安装

pip 安装
pip3 install tornado

源码安装
tar xvzf tornado-4.4.1.tar.gz
cd tornado
-4.4.1
python setup.py build
sudo python setup.py install

源码下载:tornado-1.2.1.tar.gz、 tornado-4.4.1.tar.gz

主要模块
web - FriendFeed 使用的基础 Web 框架,包含了 Tornado 的大多数重要的功能
escape - XHTML, JSON, URL 的编码 /解码方法
database - 对 MySQLdb 的简单封装,使其更容易使用
template - 基于 Python 的 web 模板系统
httpclient - 非阻塞式 HTTP 客户端,它被设计用来和 web 及 httpserver 协同工作
auth - 第三方认证的实现(包括 Google OpenID/OAuth、Facebook Platform、Yahoo BBAuth、FriendFeed OpenID/OAuth、Twitter OAuth)
locale - 针对本地化和翻译的支持
options - 命令行和配置文件解析工具,针对服务器环境做了优化

底层模块
httpserver - 服务于 web 模块的一个非常简单的 HTTP 服务器的实现
iostream
- 对非阻塞式的 socket 的简单封装,以方便常用读写操作
ioloop
- 核心的 I/O 循环

Tornado 各模块

 

二、Hello, world

 "Hello, world" 及 Application settings 基本配置:

import tornado.ioloop
import tornado.web
# import uimodules as md
# import uimethods as mt

class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write(
"Hello, world")

settings = {
'template_path': 'views', # html 文件
'static_path': 'statics', # 静态文件(css,js,img)
'static_url_prefix': '/statics/',# 静态文件前缀
'cookie_secret': 'suoning', # cookie 自定义字符串加盐
# 'xsrf_cookies': True, # 防止跨站伪造
# 'ui_methods': mt, # 自定义 UIMethod 函数
# 'ui_modules': md, # 自定义 UIModule 类
}

application = tornado.web.Application([
(r
"/", MainHandler),
],
**settings)

if name == "main":
application.listen(
8888)
tornado.ioloop.IOLoop.instance().start()

 

三、方法

 1、处理程序和参数

  请求来时,程序会用正则匹配相应路由地址,并交付于 tornado.web.RequestHandler 的子类处理;子类会根据请求方式(post / get / delete ...)的不同调用并执行相应的方法,方法返回字符串内容并发送到浏览器。

self.write("<h1>Hello, World</h1>")    # html 代码直接写在浏览器客户端
self.render("index.html")  # 返回 html 文件, 调用 render_string(), 内部其实是打开并读取文件, 返回内容
self.redirect("http://www.cnblogs.com/suoning",permanent=False) # 跳转重定向, 参数代表是否永久重定向

name = self.get_argument("name")       # 获取客户端传入的参数值
name = self.get_arguments("name")      # 获取多个值,类别形式
file = self.request.files["filename"]  # 获取客户端上传的文件

raise tornado.web.HTTPError(403) # 返回错误信息给客户端

2、重写 RequestHandler 的方法函数

对于一个请求的处理过程代码调用次序如下:

  1. 程序为每一个请求创建一个 RequestHandler 对象;
  2. 程序调用 initialize() 函数,这个函数的参数是 Application 配置中的关键字参数定义。(initialize 方法是 Tornado 1.1 中新添加的,旧版本中你需要重写 __init__ 以达到同样的目的) initialize 方法一般只是把传入的参数存到成员变量中,而不会产生一些输出或者调用像 send_error 之类的方法。
  3. 程序调用 prepare()。无论使用了哪种 HTTP 方法,prepare 都会被调用到,因此这个方法通常会被定义在一个基类中,然后在子类中重用。prepare可以产生输出信息。如果它调用了finish(或 send_error` 等函数),那么整个处理流程就此结束。
  4. 程序调用某个 HTTP 方法:例如 get()post()put() 等。如果 URL 的正则表达式模式中有分组匹配,那么相关匹配会作为参数传入方法。

 重写 initialize() 函数(会在创建 RequestHandler 对象后调用):

class ProfileHandler(tornado.web.RequestHandler):
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> initialize(self,database):
    self.database </span>=<span style="color: rgba(0, 0, 0, 1)"> database

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get(self):
    self.write(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">result:</span><span style="color: rgba(128, 0, 0, 1)">"</span> +<span style="color: rgba(0, 0, 0, 1)"> self.database)

application = tornado.web.Application([
(r
"/init", ProfileHandler, dict(database="database"))
])

 

四、模板引擎

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

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

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

注:在使用模板前需要在 setting 中设置模板路径:"template_path" : "views"

 1、基本使用

#!/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
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Nick</title>
</head>
<body>
&lt;div&gt;
    &lt;ul&gt;<span style="color: rgba(0, 0, 0, 1)">
        {</span>% <span style="color: rgba(0, 0, 255, 1)">for</span> item <span style="color: rgba(0, 0, 255, 1)">in</span> list_info %<span style="color: rgba(0, 0, 0, 1)">}
            </span>&lt;li&gt;{{item}}&lt;/li&gt;<span style="color: rgba(0, 0, 0, 1)">
        {</span>% end %<span style="color: rgba(0, 0, 0, 1)">}
    </span>&lt;/ul&gt;
&lt;/div&gt;

</body>
</html>

index.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 的別名

其他方法

2、母版

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Nick</title>
    <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
    {% block CSS %}{% end %}
</head>
<body>
&lt;div <span style="color: rgba(0, 0, 255, 1)">class</span>=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">pg-header</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;

&lt;/div&gt;<span style="color: rgba(0, 0, 0, 1)">

{</span>% block RenderBody %}{% end %<span style="color: rgba(0, 0, 0, 1)">}

</span>&lt;script src=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">{{static_url(</span><span style="color: rgba(128, 0, 0, 1)">"</span>js/jquery-1.8.2.min.js<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">)}}</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;&lt;/script&gt;<span style="color: rgba(0, 0, 0, 1)">

{</span>% block JavaScript %}{% end %<span style="color: rgba(0, 0, 0, 1)">}

</body>
</html>

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

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

&lt;ul&gt;<span style="color: rgba(0, 0, 0, 1)">
{</span>%  <span style="color: rgba(0, 0, 255, 1)">for</span> item <span style="color: rgba(0, 0, 255, 1)">in</span> li %<span style="color: rgba(0, 0, 0, 1)">}
    </span>&lt;li&gt;{{item}}&lt;/li&gt;<span style="color: rgba(0, 0, 0, 1)">
{</span>% end %<span style="color: rgba(0, 0, 0, 1)">}
</span>&lt;/ul&gt;<span style="color: rgba(0, 0, 0, 1)">

{% end %}

{% block JavaScript %}

{% end %}

index.html

3、导入

<div>
    <ul>
        <li>1024</li>
        <li>42 区 </li>
    </ul>
</div>
header.html
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Nick</title>
    <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
</head>
<body>
&lt;div <span style="color: rgba(0, 0, 255, 1)">class</span>=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">pg-header</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;<span style="color: rgba(0, 0, 0, 1)">
    {</span>% include <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">header.html</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)">}
</span>&lt;/div&gt;

&lt;script src=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">{{static_url(</span><span style="color: rgba(128, 0, 0, 1)">"</span>js/jquery-1.8.2.min.js<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">)}}</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;&lt;/script&gt;

</body>
</html>

index.html

4、自定义 UIMethod 以 UIModule

a. 定义

# uimethods.py

def tab(self):
return 'UIMethod'

uimethods.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from tornado.web import UIModule
from tornado import escape

class custom(UIModule):

</span><span style="color: rgba(0, 0, 255, 1)">def</span> render(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> escape.xhtml_escape(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">&lt;h1&gt;nick&lt;/h1&gt;</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">return escape.xhtml_escape('&lt;h1&gt;suoning&lt;/h1&gt;')</span></pre>
uimodules.py

b. 注册

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
from tornado.escape import linkify
import uimodules as md
import uimethods as mt

class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render(
'index.html')

settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'ui_methods': mt,
'ui_modules': md,
}

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

if name == "main":
application.listen(
8009)
tornado.ioloop.IOLoop.instance().start()

View Code

c. 使用

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Nick</title>
    <link href="{{static_url("commons.css")}}" rel="stylesheet" />
</head>
<body>
    <h1>hello</h1>
    {% module custom(123) %}
    {{tab() }}
</body>
View Code

 

 五、静态文件和主动式文件缓存

 在应用配置 settings 中指定 static_path 选项来提供静态文件服务;

 在应用配置 settings 中指定 static_url_prefix 选项来提供静态文件前缀服务;

 在导入静态文件时用 {{static_url('XX.css')}} 方式实现主动缓存静态文件

settings = {
    'template_path': 'views',
    'static_path': 'static',
    'static_url_prefix': '/static/',
}
<head lang="en">
    <title>Nick</title>
    <link href="{{static_url("commons.css")}}" rel="stylesheet" />
</head>

 

六、 Cookie

1、基本 Cookie

set_cookie 方法在用户的浏览中设置 cookie;

get_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!")

2、加密 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=")

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 </span>=<span style="color: rgba(0, 0, 0, 1)"> utf8(str(int(clock())))
value </span>=<span style="color: rgba(0, 0, 0, 1)"> base64.b64encode(utf8(value))
</span><span style="color: rgba(0, 0, 255, 1)">if</span> version == 1<span style="color: rgba(0, 0, 0, 1)">:
    signature </span>=<span style="color: rgba(0, 0, 0, 1)"> _create_signature_v1(secret, name, value, timestamp)
    value </span>= b<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">|</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">.join([value, timestamp, signature])
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> value
</span><span style="color: rgba(0, 0, 255, 1)">elif</span> version == 2<span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> The v2 format consists of a version number and a series of</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> length-prefixed fields "%d:%s", the last of which is a</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> signature, all separated by pipes.  All numbers are in</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> decimal format with no leading zeros.  The signature is an</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> HMAC-SHA256 of the whole string up to that point, including</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> the final pipe.</span>
    <span style="color: rgba(0, 128, 0, 1)">#

# 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
''])

    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(secret, dict):
        </span><span style="color: rgba(0, 0, 255, 1)">assert</span> key_version <span style="color: rgba(0, 0, 255, 1)">is</span> <span style="color: rgba(0, 0, 255, 1)">not</span> None, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Key version must be set when sign key dict is used</span><span style="color: rgba(128, 0, 0, 1)">'</span>
        <span style="color: rgba(0, 0, 255, 1)">assert</span> version &gt;= 2, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Version must be at least 2 for key version support</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">
        secret </span>=<span style="color: rgba(0, 0, 0, 1)"> secret[key_version]

    signature </span>=<span style="color: rgba(0, 0, 0, 1)"> _create_signature_v2(secret, to_sign)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> to_sign +<span style="color: rgba(0, 0, 0, 1)"> signature
</span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 0, 255, 1)">raise</span> ValueError(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Unsupported version %d</span><span style="color: rgba(128, 0, 0, 1)">"</span> %<span style="color: rgba(0, 0, 0, 1)"> 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 </span>= value[2:]  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> remove version number</span>
key_version, rest =<span style="color: rgba(0, 0, 0, 1)"> _consume_field(rest)
timestamp, rest </span>=<span style="color: rgba(0, 0, 0, 1)"> _consume_field(rest)
name_field, rest </span>=<span style="color: rgba(0, 0, 0, 1)"> _consume_field(rest)
value_field, passed_sig </span>=<span style="color: rgba(0, 0, 0, 1)"> _consume_field(rest)
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> 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)]

</span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> isinstance(secret, dict):
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
        secret </span>=<span style="color: rgba(0, 0, 0, 1)"> secret[key_version]
    </span><span style="color: rgba(0, 0, 255, 1)">except</span><span style="color: rgba(0, 0, 0, 1)"> KeyError:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None

expected_sig </span>=<span style="color: rgba(0, 0, 0, 1)"> _create_signature_v2(secret, signed_string)
</span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> _time_independent_equals(passed_sig, expected_sig):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
</span><span style="color: rgba(0, 0, 255, 1)">if</span> name_field !=<span style="color: rgba(0, 0, 0, 1)"> utf8(name):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
timestamp </span>=<span style="color: rgba(0, 0, 0, 1)"> int(timestamp)
</span><span style="color: rgba(0, 0, 255, 1)">if</span> timestamp &lt; clock() - max_age_days * 86400<span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> The signature has expired.</span>
    <span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
</span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">:
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> base64.b64decode(value_field)
</span><span style="color: rgba(0, 0, 255, 1)">except</span><span style="color: rgba(0, 0, 0, 1)"> Exception:
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> 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

</span><span style="color: rgba(0, 0, 255, 1)">return</span> key_version</pre>
内部算法

加密 Cookice 的本质:

写 cookie 过程:

  • 将值进行 base64 加密
  • 对除值以外的内容进行签名,哈希算法(无法逆向解析)
  • 拼接 签名 + 加密值

读 cookie 过程:

  • 读取 签名 + 加密值
  • 对签名进行验证
  • base64 解密,获取值内容

注:许多 API 验证机制和安全 cookie 的实现机制相同。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get(self):
    login_user </span>= self.get_secure_cookie(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">login_user</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">, None)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> login_user:
        self.write(login_user)
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
        self.redirect(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">/login</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.current_user()

    self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login.html</span><span style="color: rgba(128, 0, 0, 1)">'</span>, **{<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">status</span><span style="color: rgba(128, 0, 0, 1)">'</span>: <span style="color: rgba(128, 0, 0, 1)">''</span><span style="color: rgba(0, 0, 0, 1)">})

</span><span style="color: rgba(0, 0, 255, 1)">def</span> post(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):

    username </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    password </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">pwd</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> username == <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">nick</span><span style="color: rgba(128, 0, 0, 1)">'</span> <span style="color: rgba(0, 0, 255, 1)">and</span> password == <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">nicknick</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">:
        self.set_secure_cookie(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login_user</span><span style="color: rgba(128, 0, 0, 1)">'</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">nick</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
        self.redirect(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">/</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
        self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login.html</span><span style="color: rgba(128, 0, 0, 1)">'</span>, **{<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">status</span><span style="color: rgba(128, 0, 0, 1)">'</span>: <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">用户名或密码错误</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">})

settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh'
}

application = tornado.web.Application([
(r
"/index", MainHandler),
(r
"/login", LoginHandler),
],
**settings)

if name == "main":
application.listen(
8888)
tornado.ioloop.IOLoop.instance().start()

基于 Cookie 实现用户验证 -Demo
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web

class BaseHandler(tornado.web.RequestHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get_current_user(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> self.get_secure_cookie(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">login_user</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

class MainHandler(BaseHandler):

@tornado.web.authenticated
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get(self):
    login_user </span>=<span style="color: rgba(0, 0, 0, 1)"> self.current_user
    self.write(login_user)

class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.current_user()

    self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login.html</span><span style="color: rgba(128, 0, 0, 1)">'</span>, **{<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">status</span><span style="color: rgba(128, 0, 0, 1)">'</span>: <span style="color: rgba(128, 0, 0, 1)">''</span><span style="color: rgba(0, 0, 0, 1)">})

</span><span style="color: rgba(0, 0, 255, 1)">def</span> post(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):

    username </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    password </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">pwd</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> username == <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">nick</span><span style="color: rgba(128, 0, 0, 1)">'</span> <span style="color: rgba(0, 0, 255, 1)">and</span> password == <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">nicknick</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">:
        self.set_secure_cookie(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login_user</span><span style="color: rgba(128, 0, 0, 1)">'</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">nick</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
        self.redirect(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">/</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
        self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login.html</span><span style="color: rgba(128, 0, 0, 1)">'</span>, **{<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">status</span><span style="color: rgba(128, 0, 0, 1)">'</span>: <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">用户名或密码错误</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">})

settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh',
'login_url': '/login'
}

application = tornado.web.Application([
(r
"/index", MainHandler),
(r
"/login", LoginHandler),
],
**settings)

if name == "main":
application.listen(
8888)
tornado.ioloop.IOLoop.instance().start()

基于签名 Cookie 实现用户验证 -Demo

3、JavaScript 操作 Cookie

 由于 Cookie 保存在浏览器端,所以在浏览器端也可以使用 JavaScript 来操作 Cookie

/*
设置 cookie,指定秒数过期
 */
function setCookie(name,value,expires){
    var temp = [];
    var current_date = new Date();
    current_date.setSeconds(current_date.getSeconds() + 5);
    document.cookie = name + "= "+ value +";expires=" + current_date.toUTCString();}

对于参数:

  • domain   指定域名下的 cookie
  • path       域名下指定 url 中的 cookie
  • secure    https 使用

注:jQuery 中也有指定的插件 jQuery Cookie 专门用于操作 cookie,猛击这里

 

七、用户认证

当前已经认证的用户信息都被保存在每一个请求处理器的 self.current_user 当中, 同时在模板的 current_user 中也是。默认情况下,current_user 为 None

要在应用程序实现用户认证的功能,你需要重写请求处理中 get_current_user() 这 个方法,在其中判定当前用户的状态,比如通过 cookie。下面的例子让用户简单地使用一个 nickname 登陆应用,该登陆信息将被保存到 cookie 中:

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")

class MainHandler(BaseHandler):
def get(self):
if not self.current_user:
self.redirect(
"/login")
return
name
= tornado.escape.xhtml_escape(self.current_user)
self.write(
"Hello, " + name)

class LoginHandler(BaseHandler):
def get(self):
self.write(
'<html><body><form action="/login" method="post">'
'Name: <input type="text" name="name">'
'<input type="submit" value="Sign in">'
'</form></body></html>')

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> post(self):
    self.set_secure_cookie(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">user</span><span style="color: rgba(128, 0, 0, 1)">"</span>, self.get_argument(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">))
    self.redirect(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">/</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

application = tornado.web.Application([
(r
"/", MainHandler),
(r
"/login", LoginHandler),
], cookie_secret
="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")

对于那些必须要求用户登陆的操作,可以使用装饰器 tornado.web.authenticated。 如果一个方法套上了这个装饰器,但是当前用户并没有登陆的话,页面会被重定向到 login_url(应用配置中的一个选项),上面的例子可以被改写成:

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)

如果你使用 authenticated 装饰器来装饰 post() 方法,那么在用户没有登陆的状态下, 服务器会返回 403 错误。

Tornado 内部集成了对第三方认证形式的支持,比如 Google 的 OAuth 。参阅 auth 模块 的代码文档以了解更多信息。 for more details. Checkauth 模块以了解更多的细节。在 Tornado 的源码中有一个 Blog 的例子,你也可以从那里看到 用户认证的方法(以及如何在 MySQL 数据库中保存用户数据)。

 

八、CSRF 跨站伪造请求的防范

跨站伪造请求 (Cross-site request forgery), 简称为 XSRF,是个性化 Web 应用中常见的一个安全问题。前面的链接也详细讲述了 XSRF 攻击的实现方式。

当前防范 XSRF 的一种通用的方法,是对每一个用户都记录一个无法预知的 cookie 数据,然后要求所有提交的请求中都必须带有这个 cookie 数据。如果此数据不匹配 ,那么这个请求就可能是被伪造的。

Tornado 有内建的 XSRF 的防范机制,要使用此机制,你需要在应用配置中加上 xsrf_cookies 设定:

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

如果设置了 xsrf_cookies,那么 Tornado 的 Web 应用将对所有用户设置一个 _xsrf 的 cookie 值,如果 POST PUT DELET 请求中没有这 个 cookie 值,那么这个请求会被直接拒绝。如果你开启了这个机制,那么在所有 被提交的表单中,你都需要加上一个域来提供这个值。你可以通过在模板中使用 专门的函数 xsrf_form_html() 来做到这一点:

<form action="/new_message" method="post">
  {{xsrf_form_html() }}
  <input type="text" name="message"/>
  <input type="submit" value="Post"/>
</form>

如果你提交的是 AJAX 的 POST 请求,你还是需要在每一个请求中通过脚本添加上 _xsrf 这个值。下面是在 FriendFeed 中的 AJAX 的 POST 请求,使用了 jQuery 函数来为所有请求组东添加 _xsrf 值:

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 + ")"));
}});
};

对于 PUT 和 DELETE 请求(以及不使用将 form 内容作为参数的 POST 请求) 来说,你也可以在 HTTP 头中以 X-XSRFToken这个参数传递 XSRF token。

如果你需要针对每一个请求处理器定制 XSRF 行为,你可以重写 RequestHandler.check_xsrf_cookie()。例如你需要使用一个不支持 cookie 的 API, 你可以通过将 check_xsrf_cookie() 函数设空来禁用 XSRF 保护机制。然而如果 你需要同时支持 cookie 和非 cookie 认证方式,那么只要当前请求是通过 cookie 进行认证的,你就应该对其使用 XSRF 保护机制,这一点至关重要。

 

九、文件上传

1、Form 表单上传

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title> 上传文件 </title>
</head>
<body>
    <form id="my_form" name="form" action="/index" method="POST"  enctype="multipart/form-data" >
        <input name="fff" id="my_file"  type="file" />
        <input type="submit" value="提交"  />
    </form>
</body>
</html>
HTML
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
def get(self):

    self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">index.html</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> post(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    file_metas </span>= self.request.files[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">fff</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">]
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> print(file_metas)</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span> meta <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> file_metas:
        file_name </span>= meta[<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">filename</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">]
        with open(file_name,</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">wb</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">) as up:
            up.write(meta[</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">body</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">])

settings = {
'template_path': 'template',
}

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

if name == "main":
application.listen(
8000)
tornado.ioloop.IOLoop.instance().start()

Python

2、AJAX 上传

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="file" id="img" />
    <input type="button" onclick="UploadFile();" />
    <script>
        function UploadFile(){
            var fileObj = document.getElementById("img").files[0];
        var form </span>=<span style="color: rgba(0, 0, 0, 1)"> new FormData();
        form.append(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">k1</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">v1</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
        form.append(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">fff</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">, fileObj);

        var xhr </span>=<span style="color: rgba(0, 0, 0, 1)"> new XMLHttpRequest();
        xhr.open(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">post</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">/index</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">, true);
        xhr.send(form);
    }
</span>&lt;/script&gt;

</body>
</html>

HTML - XMLHttpRequest
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <input type="file" id="img" />
    <input type="button" onclick="UploadFile();" />
    <script>
        function UploadFile(){
            var fileObj = $("#img")[0].files[0];
            var form = new FormData();
            form.append("k1", "v1");
            form.append("fff", fileObj);
        $.ajax({
            type:</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">POST</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">,
            url: </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">/index</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">,
            data: form,
            processData: false,  </span>// tell jQuery <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> to process the data
            contentType: false,  </span>// tell jQuery <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> to set contentType
            success: function(arg){
                console.log(arg);
            }
        })
    }
</span>&lt;/script&gt;

</body>
</html>

HTML - jQuery
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="my_form" name="form" action="/index" method="POST"  enctype="multipart/form-data" >
        <div id="main">
            <input name="fff" id="my_file"  type="file" />
            <input type="button" name="action" value="Upload" onclick="redirect()"/>
            <iframe id='my_iframe' name='my_iframe' src=""  class="hide"></iframe>
        </div>
    </form>
&lt;script&gt;<span style="color: rgba(0, 0, 0, 1)">
    function redirect(){
        document.getElementById(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">my_iframe</span><span style="color: rgba(128, 0, 0, 1)">'</span>).onload =<span style="color: rgba(0, 0, 0, 1)"> Testt;
        document.getElementById(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">my_form</span><span style="color: rgba(128, 0, 0, 1)">'</span>).target = <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">my_iframe</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">;
        document.getElementById(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">my_form</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">).submit();

    }
    
    function Testt(ths){
        var t </span>= $(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">#my_iframe</span><span style="color: rgba(128, 0, 0, 1)">"</span>).contents().find(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">body</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">).text();
        console.log(t);
    }
</span>&lt;/script&gt;

</body>
</html>

HTML - iframe
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
def get(self):

    self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">index.html</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> post(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    file_metas </span>= self.request.files[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">fff</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">]
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> print(file_metas)</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span> meta <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> file_metas:
        file_name </span>= meta[<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">filename</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">]
        with open(file_name,</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">wb</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">) as up:
            up.write(meta[</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">body</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">])

settings = {
'template_path': 'template',
}

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

if name == "main":
application.listen(
8000)
tornado.ioloop.IOLoop.instance().start()

Python
<script type="text/javascript">
$(document).ready(function () {

    $(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">#formsubmit</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">).click(function () {

        var iframe </span>= $(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">&lt;iframe name="postiframe" id="postiframe" style="display: none"&gt;&lt;/iframe&gt;</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">);

        $(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">body</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">).append(iframe);

        var form </span>= $(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">#theuploadform</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">);
        form.attr(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">action</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">/upload.aspx</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
        form.attr(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">method</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">post</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);

        form.attr(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">encoding</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">multipart/form-data</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
        form.attr(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">enctype</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">multipart/form-data</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);

        form.attr(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">target</span><span style="color: rgba(128, 0, 0, 1)">"</span>, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">postiframe</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
        form.attr(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">file</span><span style="color: rgba(128, 0, 0, 1)">"</span>, $(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">#userfile</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">).val());
        form.submit();

        $(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">#postiframe</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">).load(function () {
            iframeContents </span>=<span style="color: rgba(0, 0, 0, 1)"> this.contentWindow.document.body.innerHTML;
            $(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">#textarea</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">).html(iframeContents);
        });

        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> false;

    });

});

</script>

<form id="theuploadform">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>

<div id="textarea">
</div>

扩展:基于 iframe 实现 Ajax 上传示例

 

十、验证码

安装图像处理模块:pip3 install pillow

 实例截图:

验证码 Demo 源码下载:猛击这里,注意导入模块的路径

#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""blog:http://www.cnblogs.com/suoning"""
__author__ = 'Nick Suo'

import tornado.web
import tornado.ioloop
import time
import hashlib

container = {}

class Session:

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self,handler):
    self.handler </span>=<span style="color: rgba(0, 0, 0, 1)"> handler
    self.random_str </span>=<span style="color: rgba(0, 0, 0, 1)"> None

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__genarte_randmo_str</span><span style="color: rgba(0, 0, 0, 1)">(self):
    obj </span>=<span style="color: rgba(0, 0, 0, 1)"> hashlib.md5()
    obj.update(bytes(str(time.time()), encoding</span>=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf-8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">))
    random_str </span>=<span style="color: rgba(0, 0, 0, 1)"> obj.hexdigest()
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> random_str

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__setitem__</span><span style="color: rgba(0, 0, 0, 1)">(self,key,value):
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self.random_str:
        random_str </span>= self.handler.get_secure_cookie(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__tt__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> random_str:
            random_str </span>= self.<span style="color: rgba(128, 0, 128, 1)">__genarte_randmo_str</span><span style="color: rgba(0, 0, 0, 1)">()
            container[random_str] </span>=<span style="color: rgba(0, 0, 0, 1)"> {}
        </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> random_str <span style="color: rgba(0, 0, 255, 1)">not</span> <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> container.keys():
                random_str </span>= self.<span style="color: rgba(128, 0, 128, 1)">__genarte_randmo_str</span><span style="color: rgba(0, 0, 0, 1)">()
                container[random_str] </span>=<span style="color: rgba(0, 0, 0, 1)"> {}
        self.random_str </span>=<span style="color: rgba(0, 0, 0, 1)"> random_str

    container[self.random_str][key] </span>=<span style="color: rgba(0, 0, 0, 1)"> value
    self.handler.set_secure_cookie(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__tt__</span><span style="color: rgba(128, 0, 0, 1)">"</span>,self.random_str,expires_days=<span style="color: rgba(0, 0, 0, 1)">None)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getitem__</span><span style="color: rgba(0, 0, 0, 1)">(self,key):
    randmon_str </span>= self.handler.get_secure_cookie(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__tt__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
    randmon_str </span>= str(randmon_str,encoding=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf-8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> randmon_str:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
    user_info_dic </span>=<span style="color: rgba(0, 0, 0, 1)"> container.get(randmon_str,None)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> user_info_dic:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
    value </span>=<span style="color: rgba(0, 0, 0, 1)"> user_info_dic.get(key,None)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> value

class MyHandler(tornado.web.RequestHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> initialize(self):
    self.session </span>=<span style="color: rgba(0, 0, 0, 1)"> Session(self)

class LoginHandler(MyHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span> get(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    self.render(</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">login2.html</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> post(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    name </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">user</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">,None)
    pwd </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">pwd</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">,None)
    code </span>= self.get_argument(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">code</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">,None)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> self.session[<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Check_Code</span><span style="color: rgba(128, 0, 0, 1)">'</span>].upper() ==<span style="color: rgba(0, 0, 0, 1)"> code.upper():
        self.write(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">successful</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
        self.write(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">wrong</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

class CheckcodeHandler(MyHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span> get(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    </span><span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> io
    </span><span style="color: rgba(0, 0, 255, 1)">import</span><span style="color: rgba(0, 0, 0, 1)"> check_code
    mstream </span>=<span style="color: rgba(0, 0, 0, 1)"> io.BytesIO()
    img, code </span>= check_code.create_validate_code()   <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 图片和图片上的码</span>
    img.save(mstream, <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">GIF</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
    self.session[</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">Check_Code</span><span style="color: rgba(128, 0, 0, 1)">'</span>] = code   <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 把验证码存入session</span>
    self.write(mstream.getvalue())      <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 写入图片</span>
settings = { 'template_path':'views', 'static_path':'statics', 'cookie_secret':'suoning', }

application = tornado.web.Application([
(r
'/login',LoginHandler),
(r
'/check_code',CheckcodeHandler),
],
**settings)

if name == 'main':
application.listen(
8888)
tornado.ioloop.IOLoop.instance().start()

验证码实例 python 文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login by Nick</title>
</head>
<body>
    <form method="post" action="/login">
    &lt;p&gt;&lt;input name=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">user</span><span style="color: rgba(128, 0, 0, 1)">"</span> type=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">text</span><span style="color: rgba(128, 0, 0, 1)">"</span> placeholder=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">用户</span><span style="color: rgba(128, 0, 0, 1)">"</span>/&gt;&lt;/p&gt;
    &lt;p&gt;&lt;input name=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">pwd</span><span style="color: rgba(128, 0, 0, 1)">'</span> type=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">text</span><span style="color: rgba(128, 0, 0, 1)">"</span> placeholder=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">密码</span><span style="color: rgba(128, 0, 0, 1)">"</span>/&gt;&lt;/p&gt;
    &lt;p&gt;
        &lt;input name=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">code</span><span style="color: rgba(128, 0, 0, 1)">"</span> type=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">text</span><span style="color: rgba(128, 0, 0, 1)">"</span> placeholder=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">验证码</span><span style="color: rgba(128, 0, 0, 1)">"</span>/&gt;
        &lt;img src=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">/check_code</span><span style="color: rgba(128, 0, 0, 1)">"</span> onclick=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">ChangeCode();</span><span style="color: rgba(128, 0, 0, 1)">'</span> id=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">imgCode</span><span style="color: rgba(128, 0, 0, 1)">'</span>&gt;
    &lt;/p&gt;
    &lt;input type=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">submit</span><span style="color: rgba(128, 0, 0, 1)">"</span> value=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Submit</span><span style="color: rgba(128, 0, 0, 1)">"</span> /&gt; &lt;span style=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">color:red</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;&lt;/span&gt;
&lt;/form&gt;


&lt;script&gt;<span style="color: rgba(0, 0, 0, 1)">
    function ChangeCode() {

// 刷新图片
var code
= document.getElementById('imgCode');
code.src
+= '?';
}
</script>
</body>
</html>

验证码实例 HTML 文件

 

十一、非阻塞式异步请求

当一个处理请求的行为被执行之后,这个请求会自动地结束。因为 Tornado 当中使用了 一种非阻塞式的 I/O 模型,所以你可以改变这种默认的处理行为——让一个请求一直保持 连接状态,而不是马上返回,直到一个主处理行为返回。要实现这种处理方式,只需要使用 tornado.web.asynchronous 装饰器就可以了。

使用了这个装饰器之后,你必须调用 self.finish() 已完成 HTTTP 请求,否则 用户的浏览器会一直处于等待服务器响应的状态:

class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.write("Hello, world")self.finish()

下面是一个使用 Tornado 内置的异步请求 HTTP 客户端去调用 FriendFeed 的 API 的例 子:

class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch("http://friendfeed-api.com/v2/feed/bret",
                   callback=self.on_response)
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> on_response(self, response):
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> response.error: <span style="color: rgba(0, 0, 255, 1)">raise</span> tornado.web.HTTPError(500<span style="color: rgba(0, 0, 0, 1)">)
    json </span>=<span style="color: rgba(0, 0, 0, 1)"> tornado.escape.json_decode(response.body)
    self.write(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Fetched </span><span style="color: rgba(128, 0, 0, 1)">"</span> + str(len(json[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">entries</span><span style="color: rgba(128, 0, 0, 1)">"</span>])) + <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)"> entries </span><span style="color: rgba(128, 0, 0, 1)">"</span>
               <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">from the FriendFeed API</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
    self.finish()</span></pre>

例子中,当 get() 方法返回时,请求处理还没有完成。在 HTTP 客户端执行它的回 调函数 on_response() 时,从浏览器过来的请求仍然是存在的,只有在显式调用了 self.finish() 之后,才会把响应返回到浏览器。

关于更多异步请求的高级例子,可以参阅 demo 中的 chat 这个例子。它是一个使用 long polling 方式 的 AJAX 聊天室。如果你使用到了 long polling,你可能需要复写on_connection_close(), 这样你可以在客户连接关闭以后做相关的清理动作。

 

十二、自定义 Session

何为 Session?

是一种服务器端的机制,用于存储特定的用户会话所需的信息;必须依赖 cookice 。

Tornado 默认没有提供 Session 机制,我们可以自定义如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""blog:http://www.cnblogs.com/suoning"""
__author__ = 'Nick Suo'

import tornado.web
import tornado.ioloop

import time
import hashlib

container = {} # 用于存放 Session,可放在数据库,缓存等地

class Session:

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self,handler):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    :param handler: 在 initialize 方法函数里初始化,传入当前对象self
    :param handler: 客户端是否有指定 __ss__ flag
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    self.handler </span>=<span style="color: rgba(0, 0, 0, 1)"> handler
    self.random_str </span>=<span style="color: rgba(0, 0, 0, 1)"> None

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__genarte_randmo_str</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    以当前时间戳生成随机字符串
    :return: 返回随机字符串
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    obj </span>=<span style="color: rgba(0, 0, 0, 1)"> hashlib.md5()
    obj.update(bytes(str(time.time()), encoding</span>=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf-8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">))
    random_str </span>=<span style="color: rgba(0, 0, 0, 1)"> obj.hexdigest()
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> random_str

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__setitem__</span><span style="color: rgba(0, 0, 0, 1)">(self,key,value):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    设置 session 方法函数
    :param key: 设置的 key
    :param value: 设置的 value
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span>
    <span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> self.random_str:
        random_str </span>= self.handler.get_secure_cookie(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__ss__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
        </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> random_str:
            random_str </span>= self.<span style="color: rgba(128, 0, 128, 1)">__genarte_randmo_str</span><span style="color: rgba(0, 0, 0, 1)">()
            container[random_str] </span>=<span style="color: rgba(0, 0, 0, 1)"> {}
        </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">:
            </span><span style="color: rgba(0, 0, 255, 1)">if</span> random_str <span style="color: rgba(0, 0, 255, 1)">not</span> <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> container.keys():
                random_str </span>= self.<span style="color: rgba(128, 0, 128, 1)">__genarte_randmo_str</span><span style="color: rgba(0, 0, 0, 1)">()
                container[random_str] </span>=<span style="color: rgba(0, 0, 0, 1)"> {}
        self.random_str </span>=<span style="color: rgba(0, 0, 0, 1)"> random_str

    container[self.random_str][key] </span>=<span style="color: rgba(0, 0, 0, 1)"> value
    self.handler.set_secure_cookie(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__ss__</span><span style="color: rgba(128, 0, 0, 1)">"</span>,self.random_str)    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> expires_days=None</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getitem__</span><span style="color: rgba(0, 0, 0, 1)">(self,key):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)">
    获取指定 session 方法函数
    :param key: 要获取的 key
    :return: 返回获取到的值
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(0, 0, 0, 1)">
    randmon_str </span>= self.handler.get_secure_cookie(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">__ss__</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)
    randmon_str </span>= str(randmon_str,encoding=<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">utf-8</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> randmon_str:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
    user_info_dic </span>=<span style="color: rgba(0, 0, 0, 1)"> container.get(randmon_str, None)
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> <span style="color: rgba(0, 0, 255, 1)">not</span><span style="color: rgba(0, 0, 0, 1)"> user_info_dic:
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> None
    value </span>=<span style="color: rgba(0, 0, 0, 1)"> user_info_dic.get(key, None)
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> value

class MyHandler(tornado.web.RequestHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> initialize(self):
    self.session </span>=<span style="color: rgba(0, 0, 0, 1)"> Session(self)

class IndexHandler(MyHandler):

</span><span style="color: rgba(0, 0, 255, 1)">def</span> get(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    ......
    result </span>= self.session[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">"</span>]    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 获取 Session 方法函数</span>
    self.session[<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">'</span>] = <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Nick</span><span style="color: rgba(128, 0, 0, 1)">"</span>    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 设置 Session 方法函数</span>

settings = {
'template_path':'views',
'static_path':'statics',
'cookie_secret':'suoning..................',
}

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

if name == 'main':
application.listen(
8888)
tornado.ioloop.IOLoop.instance().start()