我正在为我的网站开发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()
要获得只有成分,下面应该如下
keyValue = {“title”:“api recipe”,“directions”:“测试api食谱方向”,“成分1”:“邮差”,“成分2”:“ing2”,“成分3”:“我”,“成分4” :“ingredient4”,“ingredient5”:“ingredient5”}
oldListOfKeys = keyValue.keys()
ingredientsList = filter(lambda x:x不在[“directions”,“title”],oldListOfKeys)
new Dict = {key:key Value [key] for key in key Value if key in ingredients List}
print newDict#{'ingredient4':'ingredient4','ingredient5':'ingredient5','ingredient1':'postman','ingredient2':'ing2','ingredient3':'me'}
(我在使用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']