tornado 中服务器向客户端响应json字符串

tornado 响应json字符串

import json
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options import define, parse_config_file, options
from tornado.web import Application, RequestHandler

define('port', type=int, default=8888, multiple=False)
parse_config_file('config')


class JsonRespHandler(RequestHandler):
    def get(self, *args, **kwargs):
        resp = {'key1': 'value1',
                'key2': 'value2'}
                
        # respstr = json.dumps(resp) # 将字典转换为json字符串
        # self.write(respstr) # 将json字符串响应给客户端,此时响应头中Content-Type: text/html; charset=UTF-8
        # self.set_header('Content-Type', 'application/json; charset=utf-8') # 修改响应头

        self.write(resp)
        
    def post(self, *args, **kwargs):
        pass

url_list = [('/json', JsonRespHandler)]

app = Application(url_list)
server = HTTPServer(app)
server.listen(options.port)
IOLoop.current().start()
  • 说明:
    • 方式1:直接将python中的字典返回给客户端
    • 方式2:
      • 1、将python中的字典转化为json字符串 dicstr = json.dumps(dic)
      • 2、将json字符串返回给客户端 self.write(dicstr)
      • 3、self.set_header(‘Content-Type’, ‘application/json; charset=utf-8’) 修改响应头信息

你可能感兴趣的:(tornado)