【问题标题】:Flask-Restful: Passing list into MongoDB via POST requestFlask-Restful:通过 POST 请求将列表传递到 MongoDB
【发布时间】:2014-04-03 18:38:42
【问题描述】:

我正在使用 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 documentation 中所述,但这会引发 400 - BAD REQUEST 错误。

任何想法为什么它只保存最后一个值而不是所有值作为列表?

【问题讨论】:

    标签: python mongodb pymongo command-line-interface flask-restful


    【解决方案1】:

    在 JSON 对象和 Python 字典中,名称是唯一的;您不能在此处重复 web 键并期望它起作用。改用 one web 键并将值设为列表:

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

    应该这样处理。

    【讨论】:

    • 感谢 Martijn 的快速回复。我在通过 CURL 将值作为 Web 密钥列表传递时遇到问题,但烧瓶休息时没有向我抛出 400 - Bad Request 错误。您将如何编写 CURL 命令以使其成为一个列表?我也尝试了from this question 的答案,但是当我将其用作 CURL 命令时,它会抛出 400 - Bad Request。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-12-22
      • 2015-08-27
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2021-11-01
      • 2023-03-14
      • 2018-12-09
      相关资源
      最近更新 更多