Flask AWS Dynamo DB:POST API

时间:2017-12-28 08:55:25

标签: python-3.x amazon-dynamodb flask-restful

我是DynamoDB和Flask的新手,我有端点将记录插入发电机数据库,我的有效负载看起来像这样

{
  "Address": "2013 3A New Jersey",
  "Contact_Number1": "1105632",
  "Contact_Number2": "1105632",
  "DOB": "1968-08-12",
  "Father": "FTest2",
  "First_name": "FTest2",
  "Gender": "Male",
  "Hospital_Reg_Num": "HRM123",
  "Husband": "HTest2",
  "Last_name": "LTest2",
  "Last_visit_date": "2017-11-12",
  "Mother": "MTest2",
  "patient_id": "100"
}

我的flashka api代码就像这样

def createPatient():     尝试:         userId = request.json.get('user_id')         firstName = request.json.get('First_name')         lastName = request.json.get('Last_name')         gender = request.json.get('Gender')         dob = request.json.get('DOB')     除了KeyError:         提出InvalidUsage('错误请求',status_code = 400)

print(request.json)
father = request.json.get('Father')  if 'Father' in request.json  else None
mother = request.json.get('Mother') if 'Mother' in request.json else None
husband =  request.json.get('Husband') if 'Husband' in  request.json else None
address = request.json.get('Address') if 'Address' in request.json else None
lastVisitDate= request.json.get('Last_visit_date') if 'Last_visit_date' in request.json else None

#create a new db entry
userData = {
    'user_id': { 'N': userId },
    'First_name': { 'S': firstName },
    'Last_name': { 'S': lastName },
    'Hospital_Reg_Num': { 'S': hospitalReg },
    'Gender': { 'S': gender },
    'DOB': { 'S': dob },
    'Father': { 'S': father },
    'Mother': { 'S': mother },
    'Husband': { 'S': husband },
    'Address': { 'S': address },
    'Last_visit_date': { 'S': lastVisitDate }
}

resp = client.put_item(TableName='user',Item=userData)
return jsonify(resp), 200

如果在有效载荷中我错过任何参数说父亲姓名,那么它不会插入其他记录,而是给我一个错误

Invalid type for parameter Item.Father.S, value: None, type: <class 'NoneType'>, valid types: <class 'str'>

你能帮助我如何忽略fatherName在dynamo db中插入记录?想要更新有效载荷发送的记录

1 个答案:

答案 0 :(得分:0)

不将缺少的参数设置为None,而是将它们设置为空字符串。例如:

father = request.json.get(‘Father’, ‘’)

如果找不到指定的键,则第二个arg返回默认值。