【问题标题】:In Python3 how to send jsonp to javascript在 Python3 中如何将 jsonp 发送到 javascript
【发布时间】:2014-03-14 12:47:14
【问题描述】:

在这种情况下,我使用的是 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

【问题讨论】:

    标签: javascript python json mongodb tornado


    【解决方案1】:

    RequestHandler.write() 和 RequestHandler.finish() 将为您将输入转换为 utf8 字节。首先,打开“mongo”外壳并执行:

    > 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()
    

    现在使用“mongo”外壳生成的 ObjectId 访问此 URL:

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

    您应该在浏览器中看到如下输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 2020-04-18
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      相关资源
      最近更新 更多