I'm building an API for a new web service using Python, Flask-Restful w/ pymongo.

A sample MongoDB document should look like this:

{ domain: 'foobar.com',
  attributes: { web: [ akamai,
                       google-analytics,
                       drupal,
                       ... ] } }


The imports:

from flask import Flask, jsonify
from flask.ext.restful import Api, Resource, reqparse
from pymongo import MongoClient


The class:

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


When I CURL post, I use this:

curl -i -H "Content-Type: application/json" -X POST -d '{"domain":"foobar", "web":"akamai", "web":"drupal", "web":"google-analytics"}' http://localhost:5000/v1/attributes


However, this is what gets saved in my document:

{ "_id" : ObjectId("5313a9006759a3e0af4e548a"), "attr" : { "web" : [  "google-analytics" ] }, "domain" : "foobar.com"}


It only stores the last value given in the curl for 'web'. I also tried to use the CLI command with multiple -d params as described in the reqparse documentation but that throws a 400 - BAD REQUEST error.

Any ideas how why it is only saving the last value instead of all values as a list?

有帮助吗?

解决方案

In JSON objects and in Python dictionaries, names are unique; you cannot repeat the web key here and expect it to work. Use one web key instead and make the value a list:

{"domain": "foobar", "web": ["akamai", "drupal", "google-analytics"]}

and it should be processed as such.

其他提示

In addition to @Martin Pieters answer, you would need to set your location parameter on your self.reqparse.add_argument to a tuple of json and values and the store parameter is append

self.reqparse.add_argument('domain',store='append', type = str, required = True, help = 'No domain given', location=('json','values'))
`
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top