FlaskRestful:通过POST请求将列表传递到MongoDB

2024-05-29 04:03:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python、flaskrestfulw/pymongo为新的web服务构建API。在

一个示例MongoDB文档应该如下所示:

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


进口:

^{pr2}$


课程:

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


当我卷曲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"}


它只存储“web”的curl中给出的最后一个值。我还尝试使用包含多个-d参数的CLI命令,如reqparse documentation中所述,但这抛出了一个400错误的请求错误。在

你知道为什么只保存最后一个值而不是将所有值保存为列表吗?在


Tags: 文档selfcomwebjsontruedomaingoogle
2条回答

在JSON对象和Python字典中,名称是唯一的;您不能在这里重复web键并期望它正常工作。使用一个web键,并将该值列为一个列表:

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

应该这样处理。在

除了@Martin Pieters的答案,您还需要将self.reqparse.add_argument上的location参数设置为json和{}的元组,store参数是append

self.reqparse.add_argument('domain',store='append', type = str, required = True, help = 'No domain given', location=('json','values'))
`

相关问题 更多 >

    热门问题