通过请求模块发送JSON并使用bottle.py和cherrypy捕获它 [英] Sending JSON through requests module and catching it using bottle.py and cherrypy

查看:27
本文介绍了通过请求模块发送JSON并使用bottle.py和cherrypy捕获它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a server which needs to be able to accept JSON and then process it and then send JSON back. The code at my server side is using bottle.py with cherrypy. The route in concern is the following:

@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.

为了请求此页面并测试功能,我使用了请求模块代码:

For requesting this page and testing the functionality, I'm using requests module code:

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

The data that I have to send is list of tweets. The data is itself fetched from some server which returns list of tweets. For fetching tweets, I'm using requests.get and then using json method of response object. This is working fine. Now I after some processing on this, I have to send this json, just like I fetched to another server.

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)

我不知道如何访问随请求发送的 json.

I'm not able to figure out how to gain access to the json send along the request.

推荐答案

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

For a application/json POST, simply access 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']

这篇关于通过请求模块发送JSON并使用bottle.py和cherrypy捕获它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆