线程安全
默认不是线程安全的,如果使用了多线程,则需要使用IOLoop.add_callback在finish请求之前转移控制权到主线程。
handler
initialize接收从url的初始化参数中传递的
prepare是在http方法之前调用的,只可以通过加gen.coroutine或return_future来变为异步,不能使用asynchronous。New in version 3.1: Asynchronous support.
on_finish用来清理垃圾和做日志 是在响应发送给了客户端后调用的
http method 可以使用gen.coroutine, return_future, or asynchronous,可以设置一个handler的SUPPORTED_METHODS。可实现:get head post delete patch put options。
这些方法的输入
get_arguments get_arguments get_query_argument get_query_arguments get_body_argument get_body_arguments decode_argument request path_args path_kwargs data_received(用于流式请求数据)
这些方法的输出
set_status set_header add_header clear_header set_default_headers write flush(可以传callback参数或返回一个Future) finish render render_string get_template_namespace redirect send_error write_error clear render_linked_js render_embed_css render_linked_css render_embed_js
cookie
cookies get_cookie set_cookie clear_cookie clear_all_cookies get_secure_cookie get_secure_cookie_key_version set_secure_cookie create_signed_value
tornado.web.MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1
tornado.web.MAX_SUPPORTED_SIGNED_VALUE_VERSION = 2
tornado.web.DEFAULT_SIGNED_VALUE_VERSION = 2
tornado.web.DEFAULT_SIGNED_VALUE_MIN_VERSION= 1
other
application check_etag_header check_xsrf_cookie compute_etag create_template_loader current_user get_browser_locale get_current_user get_login_url get_status get_template_path get_user_locale locale log_exception on_connection_close require_setting reverse_url set_etag_headerc static_url xsrf_token xsrf_form_html
application
class tornado.web.Application(handlers=None, default_host='', transforms=None, **settings)
handelrs
(matcher, target, [target_kwargs], [name])
(regexp, target) --> (PathMatches(regexp), target)
默认使用的就是PathMatches
此外可以使用Router HTTPMessageDelegate
target_kwargs就是会传递到initialize方法的初始参数。
(r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
We support virtual hosts with the [add_handlers]method, which takes in a host regular expression as the first argument:
application.add_handlers(r"www\.myhost\.com", [ (r"/article/([0-9]+)", ArticleHandler),])
If there’s no match for the current request’s host, then default_host parameter value is matched against host regular expressions.
settings
listen
示例化一个HTTPSever并调用它的listen方法
对于多进程下使用应该先实例化然后调用bind再调用start
之后仍然需要调用IOLoop.current().start()
add_handlers
添加一个handlers
add_handlers(host_pattern, host_handlers)
get_handler_delegate(request, target_class, target_kwargs=None, path_args=None, path_kwargs=None)
reverse_url
通过name来获得url reverse_url(name, *args) args会作为kwargs传递
log_request
装饰器
async
class MyRequestHandler(RequestHandler):
@asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self._on_download)
def _on_download(self, response):
self.write("Downloaded!")
self.finish() # 必须显示调用这个finish来响应到客户端
authenticated
表示这个函数需要用户登录后访问 如果为登录会被重定向到login url
addslash
会自动在为以斜线结尾的url后加斜线
removeslash
stream_request_body
说明这个handler是支持streaming body的
需要定义data_received在数据到达后会调用
接收文件例子
#!/usr/bin/env python
"""Usage: python file_receiver.py
Demonstrates a server that receives a multipart-form-encoded set of files in an
HTTP POST, or streams in the raw data of a single file in an HTTP PUT.
See file_uploader.py in this directory for code that uploads files in this format.
"""
import logging
try:
from urllib.parse import unquote
except ImportError:
# Python 2.
from urllib import unquote
import tornado.ioloop
import tornado.web
from tornado import options
class POSTHandler(tornado.web.RequestHandler):
def post(self):
for field_name, files in self.request.files.items():
for info in files:
filename, content_type = info['filename'], info['content_type']
body = info['body']
logging.info('POST "%s" "%s" %d bytes',
filename, content_type, len(body))
self.write('OK')
@tornado.web.stream_request_body
class PUTHandler(tornado.web.RequestHandler):
def initialize(self):
self.bytes_read = 0
def data_received(self, chunk):
self.bytes_read += len(chunk)
def put(self, filename):
filename = unquote(filename)
mtype = self.request.headers.get('Content-Type')
logging.info('PUT "%s" "%s" %d bytes', filename, mtype, self.bytes_read)
self.write('OK')
def make_app():
return tornado.web.Application([
(r"/post", POSTHandler),
(r"/(.*)", PUTHandler),
])
if __name__ == "__main__":
# Tornado configures logging.
options.parse_command_line()
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()