1

Python、Flask-Restful、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"}


「web」のカールで指定された最後の値のみを保存します。また、 reqparse のドキュメントで説明されているように、複数の -d パラメータを指定して CLI コマンドを使用しようとしましたが、400 - BAD REQUEST エラーがスローされます。

すべての値をリストとして保存するのではなく、最後の値のみを保存する理由は何ですか?

4

2 に答える 2

0

location@Martin Pietersの回答に加えて、パラメータをandself.reqparse.add_argumentのタプルに設定する必要があり、パラメータはjsonvaluesstoreappend

self.reqparse.add_argument('domain',store='append', type = str, required = True, help = 'No domain given', location=('json','values'))
`
于 2016-01-19T16:58:44.170 に答える