将数据发送到前端
1.write(chunk)
将chunk数据写到输出缓冲区。之前一直用的这种方式,例如:
class IndexHandler(RequestHandler):
def get(self):
self.write("hello,world1!")# 可以在同一个处理方法中多次使用write方法
self.write("hello,world2!")
self.write("hello,world3!")
write方法是写到缓冲区的,我们可以像写文件一样多次使用write方法不断追加响应内容,最终所有写到缓冲区的内容一起作为本次请求的响应输出。
将json数据传到前端:
import json
class IndexHandler(RequestHandler):
def get(self):
stu = {
"name":"zhangsan",
"age":24,
"gender":1,
}
stu_json = json.dumps(stu)
self.write(stu_json)
实际上,我们可以不用自己手动去做json序列化,当write方法检测到我们传入的chunk参数是字典类型后,会自动帮我们转换为json字符串。
class IndexHandler(RequestHandler):
def get(self):
stu = {
"name":"zhangsan",
"age":24,
"gender":1,
}
self.write(stu)
两种方式之间的差异:
对比一下两种方式的响应头header中Content-Type字段,自己手动序列化时为Content-Type:text/html; charset=UTF-8,而采用write方法时为Content-Type:application/json; charset=UTF-8。
write方法除了帮我们将字典转换为json字符串之外,还帮我们将Content-Type设置为application/json; charset=UTF-8。
小Tips
json的作用
实现了不同语言之间的交互
2. 设置响应头
利用set_header(name, value)方法,可以手动设置一个名为name、值为value的响应头header字段。
用set_header方法来完成上面write所做的工作:
# coding:utf-8
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import json
from tornado.web import url,RequestHandler
from tornado.options import define,options
tornado.options.define("port",default=8000,type=int,help="给个端口号呗")
class IndexHandler(RequestHandler):
def get(self):
stu = {
"name":"zhangsan",
"age":24,
"gender":1,
}
stu_json = json.dumps(stu) # 发送json数据
self.set_header("Content-Type", "application/json; charset=UTF-8")
# 设置json响应头(传输字符串的响应头:"text/html;charset=UTF-8"),这个还是放在write前面吧。
self.write(stu_json)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(
[
(r"/",IndexHandler),
],
debug = True
)
http_server = tornado.httpserver.HTTPServer(app) # 创建httpserver实例
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
3. 为所有HTTP处理方法设置响应头
set_default_headers()方法会在进入HTTP处理方法前先被调用,可以重写此方法来预先设置默认的headers。
注意:在HTTP处理方法中使用set_header()方法会覆盖掉在set_default_headers()方法中设置的同名header。