如何解析POST参数到REST服务? [英] How to parse the POST argument to a REST service?

查看:147
本文介绍了如何解析POST参数到REST服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来我还有另一个JSON问题,这次发布到REST服务。
我正在使用 Flask-Restful

  api.add_resource(Records,'/ rest / records /< string:email> /< string:password> / < string:last_sync_date>)

parser = reqparse.RequestParser()
parser.add_argument('record_date',type = str)
parser.add_argument('records' ,type = str)
parser.add_argument('rating',type = str)
parser.add_argument('notes',type = str)
$ b $ class记录(资源) :
def post(self,email,password,last_sync_date):
args = parser.parse_args()
records = args ['records']#'records'= None,但是为什么?
返回记录,201

单元测试:

  resource_fields = {
'record_date':fields.String,
'rating':fields.Integer,
'notes':fields .String,
'last_updated':fields.DateTime,
}
records = {records:[]}
records [records]。append(marshal(record1 (resource_fields))
rv = self.app.post('/ rest / records / {0} / {1} / {2}'格式(email,password,sync_date),data = json.dumps记录):

json.dumps(记录)是:

  str:{records:[{rating:1,notes:null,last_updated:Tue,15 Oct 2013 15:52:44 -0000,record_date:2013-10-15 15:52:44.746815}]} 

为什么 args ['records'] None,我清楚地通过电报发送了它?

更新:



奇怪的部分是当我发送一个单一的对象,它的所有丹迪。所以奇怪:

$ $ p $ record = dict(record_date = record1.record_date,rating = record1.rating,notes = record1.notes,last_updated = record1.last_updated)

rv = self.app.post('/ rest / records / {0} / {1} / {2}'。格式(email,password,sync_date) =记录)



args

  {'records':None,'notes':None,'task':None,'record_date':'2013-10-15 16:48:40.662744' ,'rating':'1'} 


解决方案

把这个问题提到了瓶颈问题的github上,并得到了这个解决方案,这对我很有用。 Credit to Doug Black。

reqparse并不知道如何处理JSON。为了处理JSON帖子,你需要使用flask.request.json字典。



下面是一个你可能想要的更新的例子:

  from flask进口烧瓶,从flask.ext请求
import restful
$ b $ class记录(restful.Resource) :
def post(self,email,password,last_sync_date):
records = request.json ['records']
返回记录,201

app = Flask (__name__)
api = restful.Api(app)
api.add_resource(
记录,
'/ rest / records /< string:email> /< string:密码> /< string:last_sync_date>'

request.json上的文档在这里。

你需要确保你的内容类型头文件被设置为application / json,所以flask知道填充json字典。

  self.app.post(
'/rest/records/{0}/{1}/{2}'.format (电子邮件,密码,sync_date),
dat a = json.dumps(records),
headers = {'Content-Type':'application / json'


It seems I have another JSON problem, this time when posting to the REST service. I am using Flask-Restful.

api.add_resource(Records, '/rest/records/<string:email>/<string:password>/<string:last_sync_date>')

parser = reqparse.RequestParser()
parser.add_argument('record_date', type=str)
parser.add_argument('records', type=str)
parser.add_argument('rating', type=str)
parser.add_argument('notes', type=str)

class Records(Resource):
    def post(self, email, password, last_sync_date):
        args = parser.parse_args()
        records = args['records'] # 'records' = None, but why? 
        return records, 201

Unit test:

resource_fields = {
            'record_date': fields.String,
            'rating': fields.Integer,
            'notes': fields.String,
            'last_updated': fields.DateTime,
        }
records = {"records":[]}
records["records"].append(marshal(record1, resource_fields))
    rv = self.app.post('/rest/records/{0}/{1}/{2}'.format(email, password, sync_date), data=json.dumps(records))

json.dumps(records) is:

str: {"records": [{"rating": 1, "notes": null, "last_updated": "Tue, 15 Oct 2013 15:52:44 -0000", "record_date": "2013-10-15 15:52:44.746815"}]}

Why is args['records'] None, where I am clearly sending it over the wire?

UPDATE:

Strange part is when I send a single object, its all dandy. So strange:

record = dict(record_date=record1.record_date, rating=record1.rating, notes=record1.notes, last_updated=record1.last_updated)

rv = self.app.post('/rest/records/{0}/{1}/{2}'.format(email, password, sync_date), data=record)

args:

{'records': None, 'notes': None, 'task': None, 'record_date': '2013-10-15 16:48:40.662744', 'rating': '1'}

解决方案

I ended up raising this as an issue on flask-resful github and got this solution, which works for me. Credit goes to Doug Black.

reqparse doesn't really know how to handle JSON. To deal with JSON posts, you'll want to use the flask.request.json dict.

Here's an updated example for what you probably want:

from flask import Flask, request
from flask.ext import restful

class Records(restful.Resource):
    def post(self, email, password, last_sync_date):
        records = request.json['records']
        return records, 201

app = Flask(__name__)
api = restful.Api(app)
api.add_resource(
    Records, 
    '/rest/records/<string:email>/<string:password>/<string:last_sync_date>'
)

The docs on request.json are here.

You'll need to make sure you post with the content type header set to application/json so flask knows to populate the json dictionary.

self.app.post(
    '/rest/records/{0}/{1}/{2}'.format(email, password, sync_date), 
    data=json.dumps(records), 
    headers={'Content-Type': 'application/json'
)

这篇关于如何解析POST参数到REST服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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