2017-05-24 45 views
-1

我編寫了一個Flask REST實現來接收以下數據。從客戶端接收數據時匹配JSON模式

從客戶端檢查API密鑰後,服務器應該存儲來自以下API定義的數據。我面臨的問題是,我在相同的領域'服務'下有很多字符串,我會很感激任何幫助。

{ 
    "id": "string", 
    "termsAndConditions": "string", 
    "offererBranchId": "string", 
    "requesterBranchId": "string", 
    "accepted": "2017-05-24T10:06:31.012Z", 
    "services": [ 
    { 
     "id": "string", 
     "name": "string", 
     "aggregationLevel": [ 
     "string" 
     ], 
     "aggregationMethod": [ 
     "string" 
     ], 
     "timestep": [ 
     "string" 
     ] 
    ] 
    } 
} 

我的代碼如下,如果字段名爲「服務」有一個單一的字符串,它像其他的人(即「ID」,「termsAndConditions」等)。

from flask_pymongo import PyMongo 
import json 
app = Flask(__name__) 
app.config['MONGO_DBNAME'] = 'demo' 
app.config['MONGO_URI'] = 'mongodb://[email protected]:xxxx/demo' 
mongo = PyMongo(app) 
users = mongo.db.users 
@app.route('/service-offer/confirmed/REQUESTER',methods=['POST']) 

def serviceofferconfirmed(): 
    key = request.headers.get('X-API-Key') 

    users=mongo.db.users 
    api_record=users.find_one({'name':"apikey"}) 
    actual_API_key=api_record['X-API-Key'] 
    if key==actual_API_key: 
     offer={"id": request.json["id"], 
      "termsAndConditions":request.json["termsAndConditions"], 
      "offererBranchId":request.json["offererBranchId"], 
      "requesterBranchId": request.json["requesterBranchId"], 
      "accepted":request.json["accepted"], 
      "services":request.json["services"] # Here I need help to match the schema. 
      } 
     users.insert(offer) 
     return "Service Data Successfully Stored" 
    return jsonify("Pleae check your API Key or URL") 

我希望接收整個數據是多個字符串並將數據存儲在字段名稱'services'下。

回答

1

你可以使用isinstance( 「海峽」,request.json [ 「服務」])

,如果你不希望值作爲字符串服務

if not isinstance("str", request.json["services"]): 
    // your code..........