问题描述
我正在学习 Flask 或尝试与 mongodb 一起学习,事情大多进展顺利。虽然我花了很长时间弄清楚是什么对象返回到我的 api.py 烧瓶端点的小 test_api.py。
api.py
#uses mongo engine
#simple data structure
class SimpleDocument(db.Document):
docName = db.StringField()
docAction = db.StringField()
def to_json(self):
return {"id": self.id,"name":self.docName,"action":self.docAction}
@app.route('/document/',methods=["POST"])
def add_simpledocument():
body = request.get_json()
simpledoc= SimpleDoc(**body).save()
print(simpledoc.to_json())
return simpledoc.to_json(),201 # i would like to return the object so I have the ID of the object just created too...
现在在我的 test_api.py 中:
def test_addSimpleDoc():
url = 'http://localhost:5000/document/'
headers = {'Content-Type': 'application/json'}
payload = {'name':"Simple Name Test",'action':'What the doc does'}
resp=requests.post(url,headers=headers,data=json.dumps(payload,indent=4))
print(resp.json["id"])
#cannot figure out how to get the id of the object I just created...
带有 print(resp.json["id"]) 方法的 Fials 不可下标。显然,我不知道返回给我的是什么类型的对象。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)