通过请求模块发送JSON并使用bottle.py和cherrypy捕获它

Vai*_*hek 1 python json cherrypy bottle python-requests

我有一台服务器需要能够接受JSON然后处理它然后再发送JSON.我服务器端的代码使用的是bottle.py和cherrypy.关注的路线如下:

@route ('/tagTweets', method='POST')
def tagTweets():

    response.content_type = 'application/json'

    # here I need to be able to parse JSON send along in this request.
Run Code Online (Sandbox Code Playgroud)

要请求此页面并测试功能,我正在使用请求模块代码:

我必须发送的数据是推文列表.数据本身是从某个服务器获取的,该服务器返回推文列表.对于获取推文,我正在使用requests.get然后使用响应对象的json方法.这工作正常.现在我经过一些处理,我必须发送这个json,就像我提取到另一台服务器.

url     = "http://localhost:8080/tagTweets"
data    = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r       = requests.post(url, data=json.dumps(data), headers=headers)
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何获取访问请求的json发送.

Mar*_*ers 5

对于application/jsonPOST,只需访问request.json:

@route ('/tagTweets', method='POST')
def tagTweets():
     response.content_type = 'application/json'
     sender = request.json['sender']
     receiver = request.json['receiver']
     message = request.json['message']
Run Code Online (Sandbox Code Playgroud)