我正在使用 Python、Flask-Restful w/pymongo 为新的 Web 服务构建 API。
示例 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 发布时,我使用这个:
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"}
它仅存储 curl 中为“web”提供的最后一个值。我还尝试使用带有多个 -d 参数的 CLI 命令,如reqparse 文档中所述,但这会引发 400 - BAD REQUEST 错误。
任何想法为什么它只保存最后一个值而不是所有值作为列表?