【发布时间】:2017-12-16 14:51:01
【问题描述】:
我正在为我的网站开发 API 服务。该网站是关于食谱的,用户应该在第一次访问时注册,然后登录。当他登录时,他会获得一个访问令牌,他用它来对类别和食谱进行 REST 服务。
所以来到食谱,他可以给出一个标题、成分和方向。示例:
{
"title" : "api recipe",
"directions" : "Testing api recipe directions",
"ingredient1" : "postman",
"ingredient2" : "ing2",
"ingredient3" : "me",
"ingredient4" : "ingredient4",
"ingredient5" : "ingredient5"
}
现在,当涉及到 PUT 方法时,我遇到了一个问题。我想让用户编辑一个只给出他想要编辑的食谱的食谱。示例:
{
"title" : "PUT"
}
使用 PUT 方法,如果用户提供这样的成分:
{
"ingredient2" : "Potatoes",
"ingredient5" : "stackexchange"
}
我只想更改他提供给我的成分,其余部分保持原样。
在回答我的问题之前,当用户提供上述内容时,我会得到一本包含他/她提供的键和值的字典。我的问题是,我怎样才能得到他想要编辑的所有成分以及它们的编号?
我的代码:
data = request.get_json()
category = Category.query.filter_by(user_id=user_id).filter_by(id=category_id).first()
if not category:
return jsonify({'message' : 'category does not exists'})
category.edit_recipe(data, id=recipe_id)
return jsonify({'message' : 'Edited successfully'})
def edit_recipe(self, data, *args, **kwargs):
edit_this = None
if 'id' in kwargs:
edit_this = Recipe.query.filter_by(id=kwargs['id']).filter_by(category_id=self.id).first()
else:
edit_this = Recipe.query.filter_by(title=kwargs['prev_title']).filter_by(category_id=self.id).first()
"""TODO: Get ingredient from data followed by its number.
if data == {'title' = 'change title', 'ingredient2' = 'change ing 2', 'ingredient5' = 'change ing 5'}
then I want to get keys that start with ingredient followed by their number and its value
"""
if 'title' in data:
edit_this.title = data['title']
if 'directions' in data:
edit_this.directions = data['directions']
if 'filename' in data:
edit_this.filename = data['filename']
db.session.commit()
【问题讨论】:
-
问题不清楚。您将数据保存在哪里?
-
你能在变量中看到所提供数据的地方添加代码吗?
-
好的,我已经添加了代码并解释了一下。希望现在清楚了。很抱歉第一次没有说清楚。
标签: python-3.x api dictionary flask