Tornado的安装
1、pip3安装
pip3 install tornado
2、源码安装
https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz
Tornado基本使用
import tornado.ioloop
import tornado.web
#1、 处理访问/index/的get请求: http://127.0.0.1:8888/index/
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("I am index!!")
# self.redirect('http://www.baidu.com')
# self.render('index.html',k1='v1')
#2、 处理访问 /login/的post请求和get请求: http://127.0.0.1:8888/login/
class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.write('login')
def post(self,*args,**kwargs):
self.write('login post')
#3、 配置settings
settings = {
'template_path': 'template', # 配置html文件模板位置
'static_path': 'static', # 配置静态文件路径(图片等)
'static_url_prefix': '/static/', # 前端引入静态文件路径
}
#4 路由系统
application = tornado.web.Application([
(r"/index/", MainHandler),
(r"/login/", LoginHandler),
],**settings)
#5 启动这个tornado这个程序
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Tornado各种url写法
- 无正则匹配url (http://127.0.0.1:8000/index/?nid=1&pid=2)
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
nid = self.get_query_argument('nid')
pid = self.get_query_argument('pid')
self.write("Hello, world")
# http://127.0.0.1:8000/index/?nid=1&pid=2
application = tornado.web.Application([
(r"/index/", MainHandler),
])
if __name__ == "__main__":
application.listen(8000)
tornado.ioloop.IOLoop.instance().start()
- 基于(\d+)正则的url
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self,nid,pid):
print(nid,pid)
self.write("Hello, world")
# http://127.0.0.1:8000/index/1/2/
application = tornado.web.Application([
(r"/index/(\d+)/(\d+)/", MainHandler), # 这种只能传数字
# (r"/index/(\w+)/(\w+)/", MainHandler), # 这种可以传数字、字母、下划线
])
if __name__ == "__main__":
application.listen(8000)
tornado.ioloop.IOLoop.instance().start()
- 基于正则分组(?P\d+),可以不考虑接收参数顺序 (推荐)
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self,nid,pid):
print(nid,pid)
self.write("Hello, world")
# http://127.0.0.1:8000/index/1/2/
application = tornado.web.Application([
(r"/index/(?P<nid>\d+)/(?P<pid>\d+)/", MainHandler), # 这种只能传数字
])
if __name__ == "__main__":
application.listen(8000)
tornado.ioloop.IOLoop.instance().start()
配置settings & 获取get,post请求
- settings可配置参数
settings = {
'template_path': 'template', #配置html文件模板位置
'static_path': 'static', #配置静态文件路径(图片等)
'static_url_prefix': '/static/', #前端引入静态文件路径
'ui_methods': mt,
'ui_modules': md,
'xsrf_cookies':True,
'cookie_secret':'xxx',
'login_url':"/auth/login",
'autoescape':None,
'local':"zh_CN",
'debug':True,
- 获取get、post请求
app.py
import tornado.ioloop
import tornado.web
#1、 处理访问/index/的get请求: http://127.0.0.1:9999/index
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("I am index!!")
# self.redirect('http://www.baidu.com')
# self.render('index.html',k1='v1')
#2、 处理访问 /login/的post请求和get请求: http://127.0.0.1:9999/login
class LoginHandler(tornado.web.RequestHandler):
def get(self):
#2.1 获取url中以get方式传递过来的数据: http://127.0.0.1:9999/login/?username=zhangsan
# print(self.get_query_argument('username')) # zhangsan
# print(self.get_query_arguments('username')) # ['zhangsan']
# print( self.get_argument('username') ) # get和post两种请求传递的数据都能获取
self.render('login.html')
def post(self,*args,**kwargs):
#2.2 获取请求体中以post传递的数据
# print( self.get_body_argument('faver') ) # 仅能获取单选,多选仅能获取最后一个
# print( self.get_body_arguments('faver') ) # ['1', '2', '3'] 获取多选
#2.3 get和post两种请求传递的数据都能获取
# print( self.get_argument('username') )
#2.4 设置和获取cookie
# self.cookies
# self.set_cookie()
#2.5 设置和获取请求头
# self._headers
# self.get_header()
self.write('login post')
#3、 配置settings
settings = {
'template_path': 'template', # 配置html文件模板位置
'static_path': 'static', # 配置静态文件路径(图片等)
'static_url_prefix': '/static/', # 前端引入静态文件路径
}
#4 路由系统
application = tornado.web.Application([
(r"/index/", MainHandler),
(r"/login/", LoginHandler),
],**settings)
#5 启动这个tornado这个程序
if __name__ == "__main__":
application.listen(9999)
tornado.ioloop.IOLoop.instance().start()
- /templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/base.css">
</head>
<body>
<form method="POST" action="/login/">
<input type="text" name="username">
<h5 class="c1">多选</h5>
男球:<input type="checkbox" name="faver" value="1" />
足球:<input type="checkbox" name="faver" value="2" />
皮球:<input type="checkbox" name="faver" value="3" />
<input type="submit" value="提交">
</form>
</body>
</html>
- /templates/base.css
.c1{
color: red;
}
Tornado渲染
- for循环
app.py
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", username='tom',list_info=[11, 22, 33],user_dic={'username':'zhangsan','age':77})
application = tornado.web.Application([
(r"/index", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>用户名:{{username}}</h3>
{% for item in list_info %}
<li>{{item}}</li>
{% end %}
<p></p>
{% for item in user_dic %}
<li>{{item}} : {{user_dic[item]}}</li>
{% end %}
</body>
</html>
- if、in、判断相等
app.py
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", list_info=[11, 22, 33],username='tom')
application = tornado.web.Application([
(r"/index", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if 11 in list_info %}
true
{% else %}
false
{% end %}
{% if username == "tom" %}
my name is {{username}}
{% else %}
not tom
{% end %}
</body>
</html>
Tornado多文件上传
app.py
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
def post(self, *args, **kwargs):
file_metas = self.request.files["fff"]
for meta in file_metas:
file_name = meta['filename']
with open(file_name,'wb') as up:
print('hahah')
up.write(meta['body'])
settings = {
'template_path': 'template',
}
application = tornado.web.Application([
(r"/index", MainHandler),
], **settings)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
index.html
<!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>