# -*- coding: utf-8 -*-
import tornado.web
from views import index
import config
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', index.IndexHandler),
(r'/login', index.LoginHandler, {'name': 'qzk', 'pwd': '123'}),
(r'/json', index.JsonResponseHandler), # 返回json格式的视图
(r'/header', index.HeaderHandler), # 修改响应头的视图
(r'/status', index.StatusHandler), # 修改状态码的视图
(r'/redirect', index.RedirectHandler), # 重定向的视图
(r'/error/', index.ErrorHandler), # 自定义错误的状态码以及信息的是视图
]
super(Application, self).__init__(handlers, **config.settings)
# -*- coding: utf-8 -*-
from tornado.web import RequestHandler
class IndexHandler(RequestHandler):
def get(self, *args, **kwargs):
self.write("ojbk")
class LoginHandler(RequestHandler):
def get(self,*args,**kwargs):
self.write('qwer')
三、利用wirte方法写json数据
class JsonResponseHandler(RequestHandler):
def get(self,*args,**kwargs):
response = {
"name":"qzk",
"password":"123"
}
self.write(response)
# 上述方式返回的是 json对象类型
import json
class JsonResponseHandler(RequestHandler):
def get(self,*args,**kwargs):
response = {
"name":"qzk",
"password":"123"
}
response_str = json.dumps(response)
self.write(response_str)
# 上述方式返回的 text/html 对象类型
四、设置响应头(self.set_header(name,value))
import json
class JsonResponseHandler(RequestHandler):
def get(self,*args,**kwargs):
response = {
"name":"qzk",
"password":"123"
}
response_str = json.dumps(response)
self.set_header("Content_Type","application/json;charset=UTF-8")
self.set_header("qzk","dsb")
self.write(response_str)
响应结果:
Response Headers:
Content-Length: 34
Content-Type: application/json;charset=UTF-8
Date: Mon, 12 Aug 2019 12:14:31 GMT
Etag: "df54410c9849c29be64aee44631769c071dd82bd"
Qzk: dsb
Server: TornadoServer/6.0.2
五、default_headers()-->规范默认修改响应的头的位置
class HeaderHandler(RequestHandler):
def set_default_headers(self):
# 默认修改响应的头都在这边修改
self.set_header("Content-Type", "application/json;charset=UTF-8")
self.set_header("qzk", "dsb")
def get(self, *args, **kwargs):
response = {
"name": "qzk",
"password": "456"
}
response_str = json.dumps(response)
self.write(response_str)
响应头
Response Headers:
Content-Length: 34
Content-Type: application/json;charset=UTF-8
Date: Mon, 12 Aug 2019 12:25:32 GMT
Etag: "76512585c844435efcbb60337298886e7e7b9ad3"
Qzk: dsb
Server: TornadoServer/6.0.2
六、self.set_status(status_code,reason=None)
# -*- coding: utf-8 -*-
from tornado.web import RequestHandler
class IndexHandler(RequestHandler):
def get(self, *args, **kwargs):
self.write("ojbk")
class LoginHandler(RequestHandler):
def initialize(self, name, pwd):
"""该方法在执行get之前先执行"""
self.name = name
self.pwd = pwd
def get(self, *args, **kwargs):
print(self.name, self.pwd)
self.write(self.name)
import json
class JsonResponseHandler(RequestHandler):
def get(self, *args, **kwargs):
response = {
"name": "qzk",
"password": "123"
}
response_str = json.dumps(response)
self.set_header("Content-Type", "application/json;charset=UTF-8")
self.set_header("qzk", "dsb")
self.write(response_str)
class HeaderHandler(RequestHandler):
def set_default_headers(self):
# 默认修改响应的头都在这边修改
self.set_header("Content-Type", "application/json;charset=UTF-8")
self.set_header("qzk", "dsb")
def get(self, *args, **kwargs):
response = {
"name": "qzk",
"password": "456"
}
response_str = json.dumps(response)
self.write(response_str)
class StatusHandler(RequestHandler):
def set_default_headers(self):
# 默认修改响应的头都在这边修改
self.set_header("Content-Type", "application/json;charset=UTF-8")
self.set_header("qzk", "dsb")
def get(self, *args, **kwargs):
# self.set_status(404) # 404 为系统的正常的状态码,reason可以为 None
self.set_status(999) # 999 系统不存在该状态码,因此需要设置reason,否则报错
self.write('**************')
"""
Request URL: http://127.0.0.1:8982/status
Request Method: GET
Status Code: 999 Unknown
Remote Address: 127.0.0.1:8982
Referrer Policy: no-referrer-when-downgrade
服务器端报错:
ERROR:tornado.access:999 GET /status (127.0.0.1) 1.00ms
"""
七、重定向 -- self.redirect(url)
class RedirectHandler(RequestHandler):
def get(self):
self.redirect('/')
响应头:
General:
Request URL: http://127.0.0.1:8983/redirect
Request Method: GET
Status Code: 302 Found
Remote Address: 127.0.0.1:8983
Referrer Policy: no-referrer-when-downgrade
八、self.send_error(status_code=500,**kwargs)
九、write_error(status_code,**kwargs)
class ErrorHandler(RequestHandler):
def write_error(self, status_code: int, **kwargs):
if status_code == 404:
code = 404
# 正常情况下返回的自定义的404页面
self.write('资源部存在')
elif status_code == 500:
code = 500
self.write('服务器错误')
self.set_status(code)
def get(self, *args, **kwargs):
flag = self.get_query_argument('flag')
if flag == '0':
self.send_error(404)
self.write('you are sb')
Request URL: http://127.0.0.1:8983/error/?flag=0
Request Method: GET
Status Code: 404 Not Found
Remote Address: 127.0.0.1:8983
Referrer Policy: no-referrer-when-downgrade
原文:https://www.cnblogs.com/qianzhengkai/p/11342782.html