python get请求返回json_Tornado简单Get请求返回JSON字符串(Python)

Tornado简单Get请求返回JSON字符串(Python)

发布时间:2018-03-28 15:12,

浏览次数:816

, 标签:

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'), )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值