Tornado入门–结构-解析
1. 结构
from tornado import web, ioloop
from tornado.web import url
class HelloHandler(web.RequestHandler):
#具体处理细节
def get(self): #方法名与请求方式名称一致(同Django),即处理get请求方法的方法名为get。
words = self.get_argument("words", "world") #queryset参数的获取
self.write("Hello %s" % words) #直接输出字符,使用前端页面用方法render
class MyApplication(web.Application):
def __init__(self)
url_maps = [
url(r'/hello', HelloHandler),
]
settings = dict(
debug=True,
static_path=os.path.join(BASE_DIR, 'static'), #静态文件存储路径,对应服务器物理存储路径
static_url_profix='/static/', #静态文件访问路径,对应url资源访问路径
template_path=os.path.join(BASE_DIR, 'templates'), #模板文件存放路径
)
super().__init__(url_mappings, **settings)
if __name__ == '__main__':
# 1. 创建application对象
app = MyApplication()
# 2.监听端口
app.listen(8000)
# 3.启动服务
ioloop.IOLoop.current().start()
一个Tornado Web服务程序由三部分组成:
- RequestHandler子类:用于实现每个请求对应的业务逻辑的具体细节,RequestHandler类提供相应方法。
- Application对象:全局配置,包括路由配置(负责将请求映射到对应的
RequestHanler
对象). - 启动程序:启动Web服务
2. RequestHandler 子类
2.1 简介
业务处理时,创建RequestHandler
子类来实现具体的业务处理细节,RequestHandler
类提供了很多方法帮助我们进行逻辑处理。
2.2 相应方式
Web服务器收到一个请求后,必须对其处理并返回结果(响应),响应的方式有两种:render和write。
1. render
基于模板的相应方式,必须有模板文件,可以传递参数给模板。
RequestHandler.render(template_name: str, **kwargs)
- template_name:模板名称,即html文件名;
- kwargs:字典参数,向模板文件传递变量
class PictureHandler(web.RequestHandler):
'''
展示两张图片,一张网上图片,一张服务器自己存储的图片。
'''
def get(self):
data = {
"outpicture": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1561700032957&di=4ae7cd97a8cdea7d0064c313c02d4f1e&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F15%2F13%2F29%2F75r58PIC2kt_1024.jpg",
"innerpicture": "/static/images/space.jpg",
}
return self.render("picture.html", **data)
对应的html
{% extends base.html %}
{% block content %}
<span style="font-size:15px">链接图片</span><br/>
<a href="{{ outpicture }}">
<image style="width:216px; height:150px" src="{{ outpicture }}"></image>
</a><br/>
<span style="font-size:15px">静态图片</span><br/>
<a href="{{ innerpicture }}">
<image style="width:216px; height:150px" src="{{ innerpicture }}"></image>
</a><br/>
{% end %}
<-- 变量的访问方式同Django使用{{变量名}} /-->
2. write
无需使用模板,接受字符串、字节、字典格式数据。
注:字典格式数据被转为Json,网络传输中没有字典全部为字符串
class HelloHandler(web.RequestHandler):
"""
没啥东西,就Hello world吧
"""
def get(self):
words = self.get_argument("words", "world") #获取queryset参数
self.write("Hello %s" % words)
3. Application对象
Application对象负责进行全局配置,如路由、静态文件、模板文件等等相关配置。此次仅记录路由相关配置。
3.1 基本路由配置
from tornado.web import url, RequestHandler, Application
class tornado.web.Application
def __init__(list_url, **seetings):
pass
#举个栗子
class MainHandler(RequestHandler):
def get(self):
self.write("<a href='%s'>Link to space picture</a>" % self.reverse_url("picture"))
#重定向
class PictureHandler(RequestHandler):
def initialize(self, url):#接收到参数的处理
self.url = url
def get(self):
self.render("picture.html", pic_url = self.url)
class MyApplication(Application):
_urlmappings = [
url(r'/', MainHadler),
url(r'/picture', PictureHandler, dict(url="/static/images/space.jpg"), name="picture")
#name 用于reverse_url重定向,与Django类似。
]
def __init__(self):
super().__init__(self.__class__._urlmappings)
Application对象的构造方法的第一个参数是列表类型的路由表,列表内包含若干url
对象(每个url对象负责单个路由匹配)。
url对象有4个参数,通常只用前两个:
- regExp:需要匹配的url路径,
- Handler子类:对应的业务处理类,
- 字典参数:可以向处理类传递参数,该参数必须在处理类的
initialize
方法中处理。 - name:给这一条路由命名,用于重定向。
3.2 配置启动信息
由于现在可以直接用Application对象启动web服务,所以在Application对象中可以进行一些服务器基本配置。
上例子:
import os
class MyApplication(Application):
_urlmappings = [
url(r'/', MainHadler),
url(r'/picture', PictureHandler, dict(url="/static/images/space.jpg"), name="picture")
#name 用于reverse_url重定向,与Django类似。
]
def __init__(self):
BASE_DIR = os.path.abspath(./)
settings = dict(
debug=True, #允许调试,修改代码后会立刻重启服务
static_path=os.path.join(BASE_DIR, 'static'),
static_url_profix='/static/',
template_path=os.path.join(BASE_DIR, 'templates'),
)
super().__init__(self.__class__._urlmappings, **settings)
对,就是配置这些东东。