2014-03-02 132 views
1

我正在使用Python,Flask-Restful w/pymongo爲一個新的Web服務構建一個API。Flask-Restful:通過POST請求將列表傳遞到MongoDB

樣本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 -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"} 


它只存儲最後的值捲曲'網絡'。我還嘗試使用帶有多個-d參數的CLI命令,如reqparse documentation中所述,但會引發400-BAD REQUEST錯誤。

任何想法爲什麼只是將最後一個值而不是所有值保存爲列表?

回答

1

在JSON對象和Python字典中,名稱是唯一的;你不能在這裏重複web密鑰,並期待它的工作。使用一個web鍵代替,使值的列表:

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

,它應該被處理爲此類。

+0

感謝您的回覆速度快的Martijn。我有通過CURL傳遞值作爲Web密鑰列表的問題,而沒有安靜地扔我400 - 錯誤的請求錯誤。你會如何編寫CURL命令以便它是一個列表?我也試過[這個問題]的答案(http://stackoverflow.com/questions/13368316/how-to-do-a-http-post-a-a-a-- ta-of-value-using-curl「),但這是當我將它用作CURL命令時拋出一個400 - 錯誤請求。 –

0

除了@馬丁Pieters的答案,你需要設置你的location參數上您self.reqparse.add_argumentjsonvalues元組和store參數是append

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