Tornado-请求与响应
这篇讲什么
- 一个 Tornado 工程该怎么摆(
config.py/application.py/server.py/views/四件套),以及Application那几个 settings 各自到底管到什么程度。 - 请求侧:路由的四种写法、
initialize收参数、query 与 body 分开取值、request对象的每个属性和上传文件的结构。 - 响应侧:
write与finish、两种 JSON 写法、响应头与状态码、重定向、send_error配write_error,以及static_url生成的版本串(6.6 有个路径坑,实测过)。
工程骨架
-
老笔记的骨架是按当时那套教程摆的,目录思路仍然对:把「配置、路由、启动、视图」拆成四个文件。下面这份是本机跑通过的现代版本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14project/
static/ # 静态文件
css/common.css
img/
html/index.html # 纯静态兜底页
templates/ # 模板
index.html
upfile/ # 上传落盘目录
views/ # 视图(一个业务一个模块)
__init__.py
index.py
config.py # 路径、端口、settings
application.py # 路由表 + Application
server.py # 启动入口 -
config.py只放常量,别放逻辑:config.py 1
2
3
4
5
6
7
8
9
10
11
12
13import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
OPTIONS = {"port": 8888}
SETTINGS = {
"debug": True,
"cookie_secret": "换成你自己的随机串",
"login_url": "/login",
"static_path": os.path.join(BASE_DIR, "static"),
"template_path": os.path.join(BASE_DIR, "templates"),
} -
views/index.py放处理类:views/index.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14import tornado.web
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("index ok")
class HelloHandler(tornado.web.RequestHandler):
def initialize(self, word):
self.word = word
def get(self, name):
self.write("hello %s, %s" % (name, self.word)) -
application.py只负责把路由表和 settings 交给Application:application.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14import tornado.web
import config
from views import index
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", index.IndexHandler),
tornado.web.url(r"/hello/(\w+)", index.HelloHandler,
{"word": "nice"}, name="hello"),
]
super().__init__(handlers, **config.SETTINGS) -
server.py是入口:server.py 1
2
3
4
5
6
7
8
9
10
11
12import tornado.httpserver
import tornado.ioloop
import config
from application import Application
if __name__ == "__main__":
app = Application()
http_server = tornado.httpserver.HTTPServer(app)
http_server.bind(config.OPTIONS["port"])
http_server.start(1)
tornado.ioloop.IOLoop.current().start() -
实测这份骨架跑起来的结果:
1
2
3http://127.0.0.1:8926/ -> 200 'index ok'
http://127.0.0.1:8926/hello/tyui -> 200 'hello tyui, nice'
http://127.0.0.1:8926/static/css/common.css -> 200 'body{color:#333}' -
老笔记这里还放了一整套手写的 ORM(
ORM.save()拼 SQL 字符串、SunckMySQL用装饰器做单例、每次操作都重开连接)。这套东西不建议再抄,三个硬问题:- SQL 全靠字符串拼接,参数没做转义,等于把 SQL 注入留着。
pymysql.connect(host, user, passwd, dbName)用位置参数传,换了 pymysql 版本顺序一变就错,官方要求写关键字参数。- 每次查询都新建连接、用完就关,扛不住并发,也没有连接池。
-
Tornado 自己不管数据库,官方立场就是「随便你接」。要 ORM 就用 SQLAlchemy(本系列用法见 Tornado-模板和数据库以及接口的调用顺序),要异步就用 Tortoise/asyncpg 那一类。
-
老笔记这里留了一个「拷贝基础工程」的下载按钮,思路没错,但里面的代码要按上面这几条改过再用:
以后写新项目直接拷贝基础工程即可!
Application 与 settings
Application(handlers, **settings)的settings是个普通字典,没设的键就不在settings里(实测Application([]).settings里根本没有debug、cookie_secret这些键),所以别指望「读出来是 False」,读不到就是没配。
debug 会连带改三件事
-
debug=True不只是打开调试,实测它会顺手把三项设置改掉:1
2
3
4
5
6
7
8Application([], debug=True) 的 settings:
debug True
compiled_template_cache False # 模板不缓存编译结果
static_hash_cache False # 静态文件版本串不缓存
serve_traceback True # 出错时页面给 traceback
tornado.autoreload 已导入 # 代码一改就重启
Application([], debug=False) 的这三项:全部是 None(等于没设,走默认) -
想单独控制某一项,就在
debug=True的同时显式传,实测显式值赢:1
2Application([], debug=True, compiled_template_cache=True)
-> settings['compiled_template_cache'] = True -
老笔记写的
server_traceback是拼错的,正确的键是serve_traceback(serve,不是 server)。实测写错不会报错——它只是个没人读的键,所以你以为打开了 traceback,其实没有。 -
同理,
autoreload不是独立开关,debug=True就已经包含它;单独设autoreload=True也可以,但生产环境两个都不能开。
autoescape 只认函数名和 None
-
老笔记说「
autoescape为 None 时关闭自动转义」,这条实测是对的,但要补一句:只有None和函数名两种写法有效,传布尔值直接 500。settings 写法 渲染 {{ payload }}(值是<script>alert(1)</script>)不写(默认) <script>alert(1)</script>(转义)autoescape='xhtml_escape'转义(显式指定函数名) autoescape=None<script>alert(1)</script>(不转义)autoescape=True/False500 Internal Server Error 原因是这个值最终被当成「模板命名空间里的函数名」用,传
False会生成False(value)这种代码,实测报TypeError: 'bool' object is not callable。 -
只想让某个变量不转义,别动全局,用
。实测同一个模板里三种写法(payload的值是<b>x</b>):1
2A={{ payload }} | B=[[ payload ]] | C={% raw payload %}
-> A=<b>x</b> | B=[[ payload ]] | C=<b>x</b>也就是说
{{ }}转义、{% raw %}不转义,而别处常见的[[ ]]写法在 Tornado 模板里根本不解析,会原样输出(那是 Jinja 的自定义定界符风格,不是 Tornado 的语法)。 -
其余常用的四个键:
static_path:静态目录,同时决定/static/路由的根。template_path:render()找模板的目录。cookie_secret:签名 cookie 的密钥,get_secure_cookie依赖它。xsrf_cookies/login_url:一个开 XSRF 保护,一个是未登录时跳转的地址,两者都在 Tornado-应用安全 里实测。
路由的四种写法
-
最基础的一条:正则 → 处理类。
application.py 1
2
3
4handlers = [
(r"/", index.IndexHandler),
(r"/home", index.HomeHandler),
] -
给处理类传参,用元组的第三个元素,处理类必须写
initialize接住:application.py 1
(r"/sunck", index.SunckHandler, {"word1": "nice", "word2": "handsome"}),
views/index.py 1
2
3
4
5
6
7class SunckHandler(RequestHandler):
def initialize(self, word1, word2):
self.word1 = word1
self.word2 = word2
def get(self):
self.write("sunck")-
initialize在 HTTP 方法之前调用,实测每个请求都会新建一个 handler 实例、重新走一次initialize。 -
漏写
initialize不是「参数被忽略」,而是请求直接崩,实测服务端:1
TypeError: RequestHandler._initialize() got an unexpected keyword argument 'word1'
而且异常发生在 handler 构造阶段,连接在响应之前就断了,客户端拿到的是
HTTPStreamClosedError: Stream closed,连 500 页面都看不到。
-
-
要给路由起名(给
reverse_url用),必须换成tornado.web.url(),元组写法没有地方放name:application.py 1
tornado.web.url(r"/hello/(\w+)", index.HelloHandler, {"word": "nice"}, name="hello"),
-
反向解析用
reverse_url(name, *args),实测:1
2reverse_url('kaigegood') -> /home
reverse_url('withargs', 'AAA', 'BBB') -> /w/AAA/BBB
从 URL 里取参数
-
位置分组按顺序进参数:
application.py 1
(r"/liuyifei/(\w+)/(\w+)/(\w+)", index.LiuyifeiHandler),
views/index.py 1
2
3class LiuyifeiHandler(RequestHandler):
def get(self, p1, p2, p3):
self.write("-".join([p1, p2, p3]))实测
/pos/1/2/3得到p1=1 p2=2 p3=3。 -
命名分组按名字匹配,跟分组在正则里的先后无关,这是最容易看错的一条:
application.py 1
(r"/liuyifei/(?P<p1>\w+)/(?P<p3>\w+)/(?P<p2>\w+)", index.LiuyifeiHandler),
1
GET /named/A/B/C -> p1=A p2=C p3=B
正则里第三个分组叫
p2、第二个叫p3,所以 URL 第三段的值进了p2。 -
命名分组的名称和处理类参数名对不上,实测直接 500:
1
2规则 (?P<zz>\w+) 配 def get(self, a, b, c)
-> TypeError: WrongNameHandler.get() got an unexpected keyword argument 'zz'这条和
initialize漏写是同一类问题:Tornado 不做任何宽容匹配,名字对不上就崩。
取参数
-
四个成对的方法,query 和 body 各管一半,别混:
方法 从哪取 返回 get_query_argument(name, default, strip)URL 查询串 单个值 get_query_arguments(name, strip)URL 查询串 列表 get_body_argument(name, default, strip)请求体 单个值 get_body_arguments(name, strip)请求体 列表 get_argument/get_arguments两边都查 单个值 / 列表 -
三个参数逐个实测(请求
/q?a=1&b=2&c=%20nice%20&x=1&x=2):1
2
3
4
5
6get_query_argument('a') -> '1'
get_query_argument('b', default='没有b') -> '2'
get_query_argument('c', strip=False) -> ' nice ' # 默认 strip=True 会去空格
get_query_argument('nope') -> MissingArgumentError: HTTP 400: Bad Request (Missing argument nope)
get_query_argument('x') -> '2' # 同名多个,取最后一个
get_query_arguments('x') -> ['1', '2']- 缺参数又不给
default,抛的是tornado.web.MissingArgumentError,它是 HTTP 400,浏览器看到的就是 400 页面。 - 「同名取最后一个」这条老笔记写对了,但要拿全部值只能用复数形式。
- 缺参数又不给
-
body 侧实测(
POST /body,表单体username=tyui&hobby=power&hobby=money):1
2get_body_argument('username') -> 'tyui'
get_body_arguments('hobby') -> ['power', 'money'] -
get_argument两边都查,body 优先,实测同名时:1
2
3
4请求:POST /both?k=inquery 表单体:k=inbody
get_argument('k') -> 'inbody'
get_query_argument('k') -> 'inquery'
get_body_argument('k') -> 'inbody'所以老笔记说「一般不会选用」是对的:同名时它会静默偏向 body,排查起来很费劲,明确写 query 还是 body 更好。
-
表单页要带
enctype,模板细节见 Tornado-模板和数据库以及接口的调用顺序:templates/postfile.html 1
2
3
4
5<form action="/postfile" method="post">
姓名:<input type="text" name="username"/>
爱好:<input type="checkbox" value="power" name="hobby"/>
<input type="submit" value="登陆"/>
</form>
request 对象
-
self.request是tornado.httputil.HTTPServerRequest,存的是这一次请求的全部信息。实测请求GET /req?a=1&b=2:1
2
3
4
5
6
7
8
9request.method 'GET'
request.host '127.0.0.1:8920'
request.uri '/req?a=1&b=2' # path + 查询串
request.path '/req'
request.query 'a=1&b=2'
request.version 'HTTP/1.1'
request.body b'' # GET 没有请求体
request.remote_ip '127.0.0.1'
request.files {} -
headers是HTTPHeaders(类字典),取法有两种,行为不一样,实测:1
2
3headers.get('X-Nope') -> None
headers['X-Nope'] -> KeyError: 'X-Nope'
headers.get('User-Agent') -> 'Tornado/6.6' -
取客户端 IP 只能写
request.remote_ip,写成remote_addr会AttributeError(那是 Werkzeug 那边的名字),实测日志长这样:1
2AttributeError: 'HTTPServerRequest' object has no attribute 'remote_addr'
500 GET / (127.0.0.1) 3.20ms -
上传文件在
request.files里,结构是「表单 name → 文件对象列表」。实测一个带两个file和一个img的 multipart 请求:1
2
3
4files 的键 ['file', 'img']
file -> {'filename': 'a.txt', 'content_type': 'text/plain', 'body': b'sunck is a good man'}
img -> {'filename': 't.png', 'content_type': 'image/png', 'body': b'fakepngbytes'}
元素类型 <class 'tornado.httputil.HTTPFile'>HTTPFile就是三个字段:filename(客户端给的名字)、body(字节,已经在内存里)、content_type。- 注意
body是全量读进内存的,大文件要靠MAX_BODY_SIZE(HTTPServer参数)限住,别裸收。
-
老笔记把模块名写成了
tornador.httputil,正确是tornado.httputil.HTTPFile。 -
存盘的老写法(
for两层遍历再open().write())能跑,但直接拿filename拼路径不安全:客户端可以传../../etc/x。要落盘先过werkzeug式清洗,标准做法是os.path.basename+ 自己生成随机名,实测写法:views/index.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import os
import secrets
import config
import tornado.web
class UpFileHandler(tornado.web.RequestHandler):
def post(self):
for name, file_list in self.request.files.items():
for f in file_list:
ext = os.path.splitext(f["filename"])[1].lower()
new_name = secrets.token_hex(16) + ext
path = os.path.join(config.BASE_DIR, "upfile", new_name)
with open(path, "wb") as fp:
fp.write(f["body"])
self.write("ok")用随机名还有一个好处:不用操心同名覆盖,也不用信客户端的
filename。
响应输出
write 与 finish
-
write(chunk)是往输出缓冲区追加,实测连续三次write得到的是拼接结果:1
write('AAA'); write('BBB'); write('CCC') -> 200 'AAABBBCCC'
-
请求结束时 Tornado 自动
finish();手动finish()之后再write,实测报:1
RuntimeError: Cannot write() after finish()
所以老笔记那句「finish 下边不要再 write」是对的,而且不是「不建议」,是真的会抛。
-
finish()还能直接带内容,self.finish({"a": 1})等价于write(dict)+ 结束。
两种 JSON
-
手动序列化与直接
write(dict)的差别就在Content-Type,实测:1
2
3self.write(json.dumps(per)) -> Content-Type: text/html; charset=UTF-8
self.write(per) -> Content-Type: application/json; charset=UTF-8
self.finish(per) -> Content-Type: application/json; charset=UTF-8 -
结论:接口就写
self.write(dict),别自己json.dumps,否则前端按 HTML 处理。 -
但
write(dict)只认json.dumps默认能处理的类型,实测往里塞datetime直接 500:1
2
3self.write({"t": datetime.datetime(2026, 11, 6, 19, 30)})
服务端 -> TypeError: Object of type datetime is not JSON serializable
客户端 -> 500: Internal Server Error原因在源码里很直白:
write()内部调escape.json_encode(chunk),而json_encode就一行json.dumps(value).replace("</", "<\\/")——没有任何自定义钩子。要控制序列化只能自己接管这一步,在基类里重写write:base_handler.py 1
2
3
4
5
6
7
8
9
10
11import json
from tornado.web import RequestHandler
class BaseHandler(RequestHandler):
def write(self, chunk):
if isinstance(chunk, (dict, list)):
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = json.dumps(chunk, default=str, ensure_ascii=False).replace("</", "<\\/")
super().write(chunk)1
2Content-Type: application/json; charset=UTF-8
{"t": "2026-11-06 19:30:00", "x": "<\/script>", "中文": "好"}default=str把datetime、Decimal这类兜成字符串;要精确格式就自己写default函数。- 最后那个
replace("</", "<\\/")不是可选项:escape.json_encode内置了这一步,防止 JSON 被塞进<script>时提前闭合标签,自己 dumps 就得自己补。 - 内置的
json_encode用的是json.dumps默认参数,中文会被转成\uXXXX;这里ensure_ascii=False让它原样输出,体积更小,前提是Content-Type里写清了 UTF-8。
响应头
-
set_header(name, value)在 HTTP 方法里设,set_default_headers()在进入方法之前设,后者会被前者覆盖,实测:views/index.py 1
2
3
4
5
6
7
8class HeaderHandler(RequestHandler):
def set_default_headers(self):
self.set_header("Content-Type", "text/html; charset=UTF-8")
self.set_header("X-Custom", "default")
def get(self):
self.set_header("X-Custom", "override")
self.write("header ok")1
GET /header -> X-Custom=override | Content-Type=text/html; charset=UTF-8
-
想给所有响应统一加头(比如
X-Frame-Options),就重写set_default_headers,别在每个方法里重复写。
状态码
-
set_status(code, reason=None),实测四种用法的结果:写法 结果 set_status(404)然后write404,正文照常返回 set_status(999, "who?where?what?")999,reason 生效 set_status(999)(不带 reason)999,不报错,响应体为空 先 write再set_status(404)404,正文仍在 -
这里要订正老笔记两条:
- 「
reason为 None 时状态码必须为正常值」——实测set_status(999)不传 reason 也不抛异常,只是响应里没有 reason 短语,客户端仍收到 999。 - 「
write之后再set_status会报错」——实测不报错,状态码照样改得动。真正会报错的是finish()之后再write。
- 「
-
状态码不是随便填都能用:999 这种非标准码,浏览器和代理不一定老实转发,业务里要表达「自定义错误」应该用 4xx/5xx 段内的码 + 自定义正文。
重定向
-
self.redirect(url, permanent=False),实测:1
2redirect('/') -> 302 Location: /
redirect('/', permanent=True) -> 301 Location: / -
redirect内部已经finish(),后面再写东西同样会RuntimeError,习惯上写完redirect就return。
错误页
-
send_error(status_code=500, **kwargs)主动抛一个 HTTP 错误,之后不要再输出;Tornado 会转给write_error()渲染,实测自定义错误页生效:views/index.py 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class ErrorHandler(RequestHandler):
def write_error(self, status_code, **kwargs):
if status_code == 404:
self.set_status(404)
self.write("自定义:资源不存在")
elif status_code == 500:
self.set_status(500)
self.write("自定义:服务器内部错误")
def get(self):
flag = self.get_query_argument("flag")
if flag == "0":
self.send_error(404)
return
if flag == "5":
self.send_error()
return
self.write("you are right")1
2GET /iserror?flag=0(send_error(404)) -> 404 自定义:资源不存在
GET /iserror?flag=5(send_error()) -> 500 自定义:服务器内部错误 -
没写
write_error时,默认错误页是 Tornado 自带的极简 HTML,实测未匹配路由:1
404 '<html><title>404: Not Found</title><body>404: Not Found</body></html>'
-
处理类里抛出的未捕获异常,实测也是 500 页面 + 服务端一条
Uncaught exception带 traceback;想让异常变成可读的错误码,就自己try/except后send_error。 -
老笔记把方法名拼成了
wirte_error,正确是write_error。
静态文件
-
设了
static_path,Tornado 自动挂一条/static/(.*)路由,实测直接访问就能拿到文件:1
GET /static/css/common.css -> 200 'body{color:#333}'
-
模板里要写成
static_url(...),它会附一个内容哈希版本串,实测:1
2
3
4static_url('css/common.css')
-> /static/css/common.css?v=6d2e276f5feaa02b4b210e309328fdcc462d47efa2e06f3f118f2b01ac982d5f...
按这个 URL 取回:200 | Cache-Control: max-age=315360000 | ETag: "6d2e276f..."?v=是文件内容的哈希,所以可以放心让浏览器缓存一年(max-age=315360000正好十年);文件一改哈希就变,等于自动刷新。- 缓存行为受
static_hash_cache影响,debug=True时它被关掉(见前面 debug 那节)。
-
6.6 有个必须知道的坑:
static_url的路径不能以/开头。实测:1
2
3static_url('/css/common.css') -> 403 Forbidden
服务端日志:403 GET /s: /css/common.css is not in root static directory
static_url('css/common.css') -> 200 /static/css/common.css?v=...Windows 和 Linux 上都一样(6.6 的
get_absolute_path明确拒绝跳出静态根的路径,官方 changelog 标了versionchanged:: 6.6)。老教程里那种带前导斜杠的写法现在会直接 403。 -
老笔记为了「访问根路径就发静态首页」,写了个
StaticFileHandler子类,在__init__里摸一下self.xsrf_token。实测三种写法(子类带 xsrf、子类不带、直接用内置StaticFileHandler)结果完全相同:1
2
3GET / -> 200 '<!DOCTYPE html>...Welcome to Tornado!...'
GET /index.html -> 200
GET /../css/common.css -> 403(越界被拦)也就是说这个子类没有意义,只要路由写成下面这样就够:
application.py 1
2
3(r"/(.*)", tornado.web.StaticFileHandler,
{"path": os.path.join(config.BASE_DIR, "static", "html"),
"default_filename": "index.html"}),default_filename就是「路径没指到具体文件时兜底发哪个」。- 这条兜底路由要放在路由表最后,否则它会吃掉前面所有请求。
- 越界访问(
../)由get_absolute_path拦成 403,这层保护是内置的,不用自己写。