使用导入请求测试烧瓶端点

时间:2021-04-20 02:34:06

标签: python flask flask-mongoengine

我正在学习 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 不可下标。显然,我不知道返回给我的是什么类型的对象。

0 个答案:

没有答案