tornado 入门之(http请求行为方法-路由匹配-切入点函数)【3】
http请求行为方法
主要:Get是Post两种请求方式,区别如下图
在http请求中增加参数name=仙仙,在服务器中获取请求参数方法
self.get_argument() get和post都通用
class MainHandler(tornado.web.RequestHandler):
def get(self):
name = self.get_argument('name')
print(name)
# name = self.get_query_argument('name')
self.write("Hello Python!--Get")
def post(self):
name = self.get_argument('name')
print(name)
# name = self.get_body_argument('name')
self.write("Hello Python!--Post")
cookies操作
self.set_cookie('token1','123456',expires_days=1)# 给 token1 添加cookies ,1天后自动清除
self.clear_cookie('token1') # 清除 token1 的cookies
路由匹配规则
客户端访问的http根据路由匹配相应方法
http://100.71.10.140:8080/
http://100.71.10.140:8080/res
import tornado.web # web框架模块
import tornado.ioloop # 核心IO循环模块,封装了linux的epoll和BSD的kqueue,是tornado高效的基础
import config
from tornado.options import define,options
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello Python!--Get")
# self.redirect('/') # 跳转
def post(self):
self.write("Hello Python!--Post")
class ResHandler(tornado.web.RequestHandler):
def get(self):
self.write("<h2>你好呀!</h2>")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/res", ResHandler)
])
if __name__ == "__main__":
app = make_app()
app.listen(config.options["port"])
通过 self.redirect(’/’) 可以实现路由的跳转
http请求的路由可以用正则表达式匹配
# 路由匹配规则
import tornado.web # web框架模块
import tornado.ioloop # 核心IO循环模块,封装了linux的epoll和BSD的kqueue,是tornado高效的基础
import config
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello Python!")
class DayHandler(tornado.web.RequestHandler):
def get(self,day):
self.write("%s" %day)
class Day1Handler(tornado.web.RequestHandler):
def get(self,day,month,year):
self.write("%s年%s月%s日" %(year,month,day))
class Day2Handler(tornado.web.RequestHandler):
def get(self,day,month,year):
self.write("%s年%s月%s日" %(year,month,day))
if __name__ == "__main__":
# Handlers定义路由匹配地址
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/day/(\d{4})', DayHandler),
(r'/day1/(\d{4})/(\d{2})/(\d{2})', Day1Handler),
(r'/day2/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', Day2Handler)
])
app.listen(config.options["port"])
tornado.ioloop.IOLoop.current().start()
运行结果:
两种路由获取:一个是直接按顺序传参;后者定义参数,再进行赋值
切入点函数顺序
class ResHandler(tornado.web.RequestHandler):
def initialize(self):# 初始时执行
print("initialize")
def prepare(self): # 预先执行
print("prepare")
def get(self):
print("get")
self.write("get")
def on_finish(self):# 结束时执行
print("on_finish")