我正在使用Python,Flask-Restful w/pymongo为一个新的Web服务构建一个API。Flask-Restful:通过POST请求将列表传递到MongoDB
样本MongoDB的文件应该是这样的:
{ domain: 'foobar.com',
attributes: { web: [ akamai,
google-analytics,
drupal,
... ] } }
进口:
from flask import Flask, jsonify
from flask.ext.restful import Api, Resource, reqparse
from pymongo import MongoClient
类:
class AttributesAPI(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('domain', type = str, required = True, help = 'No domain given', location='json')
self.reqparse.add_argument('web', type = str, action='append', required = True, help = 'No array/list of web stuff given', location = 'json')
super(AttributesAPI, self).__init__()
def post(self):
args = self.reqparse.parse_args()
post = db.core.update( {'domain': args['domain']},
{'$set':{'attr': { 'web': args['web'] }}},
upsert=True)
return post
当我卷曲后,我用这个:
curl -i -H "Content-Type: application/json" -X POST -d '{"domain":"foobar", "web":"akamai", "web":"drupal", "web":"google-analytics"}' http://localhost:5000/v1/attributes
然而,这是获取保存在我的文档:
{ "_id" : ObjectId("5313a9006759a3e0af4e548a"), "attr" : { "web" : [ "google-analytics" ] }, "domain" : "foobar.com"}
它只存储最后的值卷曲'网络'。我还尝试使用带有多个-d参数的CLI命令,如reqparse documentation中所述,但会引发400-BAD REQUEST错误。
任何想法为什么只是将最后一个值而不是所有值保存为列表?
感谢您的回复速度快的Martijn。我有通过CURL传递值作为Web密钥列表的问题,而没有安静地扔我400 - 错误的请求错误。你会如何编写CURL命令以便它是一个列表?我也试过[这个问题]的答案(http://stackoverflow.com/questions/13368316/how-to-do-a-http-post-a-a-a-- ta-of-value-using-curl“),但这是当我将它用作CURL命令时抛出一个400 - 错误请求。 –