tornado.web.RequestHandler
利用http协议向服务器传参
-
提取uri的特定部分
http://127.0.0.1:8091/doc/3 (r'/doc/(\d+)', DocHandler) class DocHandler(RequestHandler): def get(self, doc_id, *args, **kwargs): self.write(doc_id)
分组起名
(r'/doc/(?P<document_id>\d+)', DocHandler) class DocHandler(RequestHandler): def get(self, document_id, *args, **kwargs): self.write(document_id)
-
查询字符串(get方式)
self.get_query_argument(name,default=ARG_DEFAULT,strip=True) # 从get请求中参数字符串中获取指定参数的值 name 如果出现多个同名参数,返回最后一个值 default 设置默认值,缺省值为ARG_DEFAULT。 如果default没有设置,会抛出tornado.web.MissingArgumentError异常。 strip 去除两边的空格,缺省值为True
self.get_query_arguments(name,strip=True) # 从get请求中参数字符串中获取指定参数的值 # 返回值为一个列表
-
请求体携带数据(post方式)
self.get_body_argument(name,default=ARG_DEFAULT,strip=True) # 获取一个 self.get_body_arguments(name,default=ARG_DEFAULT,strip=True) # 获取多个
-
get & post
self.get_argument(name,default=ARG_DEFAULT,strip=True) # 获取一个 self.get_arguments(name,default=ARG_DEFAULT,strip=True) # 获取多个
-
在http报文的头中添加自定义字段
待补充
self.request
-
作用
存储了关于请求的相关信息
-
属性
-
method:http请求方式
GET
-
host:被请求的主机名
127.0.0.1:8000
-
uri:请求的完整资源地址,包括路径和查询参数部分
/docment?a=1&b=2
-
path :请求的路径部分
/document
-
query:请求参数部分
a=1&b=2
-
version:使用的http版本
HTTP/1.1 # 特点长链接
-
headers:请求头,字典类型
-
body:请求体数据
-
remote_ip:客户端ip
-
files:用户上传的文件,字典类型
{ 'file':[ { 'filename':'', 'body':'', 'content_type':'' } ] }
-
tornado.httputil.HTTPFile
-
一个文件对应一个HTTPFile文件对象
-
属性:
-
filename:文件名
-
body:文件数据实体
-
Content_type:文件类型
text/plain image/png
-
-
示例
文件上传
#!/usr/bin/env python # -*- coding: UTF-8 -*- import tornado.ioloop import tornado.web import os class UploadFileHandler(tornado.web.RequestHandler): def get(self): self.write(''' <html> <head><title>Upload File</title></head> <body> <form action='file' enctype="multipart/form-data" method='post'> <input type='file' name='file'/><br/> <input type='submit' value='submit'/> </form> </body> </html> ''') def post(self): #文件的暂存路径 upload_path=os.path.join(os.path.dirname(__file__),'files') #提取表单中‘name’为‘file’的文件元数据 file_metas=self.request.files['file'] for meta in file_metas: filename=meta['filename'] filepath=os.path.join(upload_path,filename) #有些文件需要已二进制的形式存储,实际中可以更改 with open(filepath,'wb') as up: up.write(meta['body']) self.write('finished!') app=tornado.web.Application([ (r'/file',UploadFileHandler), ]) if __name__ == '__main__': app.listen(3000) tornado.ioloop.IOLoop.instance().start()
文件下载
def post(self,filename): print('i download file handler : ',filename) #Content-Type这里我写的时候是固定的了,也可以根据实际情况传值进来 self.set_header ('Content-Type', 'application/octet-stream') self.set_header ('Content-Disposition', 'attachment; filename='+filename) #读取的模式需要根据实际情况进行修改 with open(filename, 'rb') as f: while True: data = f.read(buf_size) if not data: break self.write(data) #记得要finish self.finish()
网友评论