我正在为我的网站开发API服务。该网站是关于食谱的,用户应该在第一次访问时注册,然后登录。当他登录时,他获得了一个访问令牌,用于在类别和食谱上进行REST服务。
所以来到食谱,他可以给出标题,成分和方向。例如:
{
"title" : "PUT"
}
现在,在PUT方法方面我遇到了一个问题。我想让用户编辑一个只给出他想编辑的配方。例如:
{
"ingredient2" : "Potatoes",
"ingredient5" : "stackexchange"
}
使用PUT方法,如果用户提供了这样的成分:
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()
我只想改变他提供给我的成分,并将其余部分保留原样。
在回答我的问题之前,当用户提供上述内容时,我会得到一张包含他/她提供的密钥和值的字典。我的问题是,我怎样才能获得他想要编辑的所有成分加上他们的编号?
我的代码:
{{1}}
答案 0 :(得分:1)
要仅获取成分,以下内容
keyValue = { “标题”:“api食谱”, “方向”:“测试api食谱方向”, “ingredient1”:“邮差”, “ingredient2”:“ing2”, “ingredient3”:“我”, “ingredient4”:“ingredient4”, “ingredient5”:“ingredient5” }
oldListOfKeys = keyValue.keys()
ingredientsList = filter(lambda x:x不在[“directions”,“title”],oldListOfKeys)
newDict = {key:keyValue [key] for keyValue,如果keyList中的键}}
print newDict#{'ingredient4':'ingredient4','ingredient5':'ingredient5','ingredient1':'postman','ingredient2':'ing2','ingredient3':'me'}
答案 1 :(得分:0)
(我在带有sqlAlchemy的烧瓶应用程序中使用它 - 希望它有帮助) 在put方法中,首先查询特定配方,例如
recipe = Recipe.query.filter_by(recipe_id=id).first()
然后您可以访问这样的特定键
data = request.get_json()
recipe.title = data['title']
recipe.directions = data['directions']
recipe.ingredient1 = data['ingredient1']
recipe.ingredient2 = data['ingredient2']