Tornado簡單Get請求返回JSON字符串(Python)

from tornado import gen
from tornado.web import RequestHandler
from tornado.escape import json_decode, json_encode, utf8
import json


class BaseHandler(RequestHandler):
    """解決JS跨域請求問題"""
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET')
        self.set_header('Access-Control-Max-Age', 1000)
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Content-type', 'application/json')


class IndexHandler(BaseHandler):
    """首頁處理Handler"""
    def initialize(self, data):
        self.data = data
        print(self.data)

    @gen.coroutine  # 使得方法異步處理
    def prepare(self):
        '''所有請求的初始化執行'''
        self.cur = self.application.db.cursor()

    def get(self, *args, **kwargs):
        print(args)
        sql = """
            select id, type_name from tb_types;
        """
        self.cur.execute(sql)
        res = self.cur.fetchall()
        result = {
            'status': True,
            'code': 200,
        }
        l = list()
        for re in res:
            ids = re[0]
            d = {'id': ids, 'type_name': re[1]}
            sql2 = "select id, sectype_name from tb_sectype where types_id=" + str(ids) + ";"
            self.cur.execute(sql2)
            two = list()
            for t in self.cur.fetchall():
                two.append({'id': t[0], 'sectype_name': t[1]})
            d['two'] = two
            l.append(d)
        result['result'] = l
        self.write(json.dumps(result, ensure_ascii=False))

    def post(self, *args, **kwargs):
        result = {
            "result": 'success',
            'status': True,
            'code': 200
        }
        self.write(json_encode(result))

    @gen.coroutine   # 使得方法異步處理
    def on_finish(self):
        '''在一個請求結束後被調用'''
        self.cur.close()
urls = (
    url(r'/(\d*)', IndexHandler, dict(data='user123456'), name='index'),
)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章