在Python3中如何将jsonp发送到javascrip

2024-05-15 00:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

其实这段原始代码来自互联网,但由python2编写,无法运行 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

Tags: fromselfjsonbytescallbackthisargumentclass
1条回答
网友
1楼 · 发布于 2024-05-15 00:26:31

在请求处理程序.write()和请求处理程序.finish()将为您将输入转换为utf8字节。首先,打开“mongo”shell并执行以下操作:

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

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

^{pr2}$

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

^{3}$

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

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

相关问题 更多 >

    热门问题