在Python3中如何将jsonp发送到javascript

时间:2014-03-14 12:47:15

标签: javascript python json mongodb tornado

在这个案例中我使用的是Tornado网站 我只是想用一些简单的方法将json数据从mongodb发送到javascript。 我只是在互联网上查看一些例子。我很困惑 最后我得到了结果,Python 2网络允许你通过字符串发送消息 Python 3必须是字节

实际上这个来自互联网的原始代码但是由python 2编写,无法运行 python3

from tornado.web import RequestHandler  # this Tornado standard 

class JSONPHandler(RequestHandler):
    CALLBACK = 'jsonp' # define callback argument name <== this Javascript send to python callback name, java script send msg look like ?jsonp=?  check it 
    def finish(self, chunk=None):
        assert not self._finished
        if chunk: self.write(chunk)
        # get client callback method 
        print(type(self.CALLBACK)) <==show string class  
        callbacka = self.get_argument(self.CALLBACK)
        callback=bytes(callbacka+'(','utf-8') <== from this part to  new 
        # format output with jsonp
        self._write_buffer.insert(0,callback ) <== write some json head 
        self._write_buffer.append(bytes(')','utf-8'))  <== all msg must be bytes 
        super(JSONPHandler, self).finish()  <== must do finished step 
        # chunk must be None

1 个答案:

答案 0 :(得分:1)

RequestHandler.write()和RequestHandler.finish()会将输入转换为utf8字节。首先,打开&#34; mongo&#34; shell并做:

> use test
switched to db test
> db.collection.insert({key: 'value'})
> db.collection.find()
{ "_id" : ObjectId("53232a5c8d12c74bb1a30bc1"), "key" : "value" }

注意这里生成的ObjectId。这是使用JSONP和PyMongo的代码示例:

import bson.json_util
import pymongo
from bson import ObjectId
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, HTTPError, Application

db = pymongo.MongoClient().test


class JSONPHandler(RequestHandler):
    def get(self):
        jsonp_callback_name = self.get_argument('jsonp')
        oid = self.get_argument('id')
        doc = db.collection.find_one(ObjectId(oid))
        if not doc:
            raise HTTPError(404)

        # bson.json_util handles nonstandard types like ObjectId.
        self.finish('%s(%s)' % (
            jsonp_callback_name,
            bson.json_util.dumps(doc)))

application = Application(
    [('/api', JSONPHandler)]
)

if __name__ == '__main__':
    application.listen(8888)
    IOLoop.current().start()

现在使用从&#34; mongo&#34;生成的ObjectId访问此URL。壳:

http://localhost:8888/api?jsonp=mycallback&id=53232a5c8d12c74bb1a30bc1

您应该在浏览器中看到这样的输出:

mycallback({"_id": {"$oid": "53232a5c8d12c74bb1a30bc1"}, "key": "value"})