我正在处理一个PUT
请求,以便能够使用Flask和Python修改JSON文件中的数据。问题是它不会保存所做的更改。
以下是我的代码:
@app.route('/updated', methods = ['POST', 'PUT' 'GET'])
def update():
try:
title = request.form['title']
print title
if request.method == 'POST':
with open("articles.json", 'r+') as json_File:
articles = json.load(json_File)
for article in articles['article']:
if title == article['title']:
print article['title']
print article['author']
print article['article_id']
article['title'] = title
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
print article
save_article = json.dumps(article, json_File)
else:
print "article could not be added"
#json_File.close()
return render_template('updated.html', save_article = save_article, article = article)
except:
print "This didn't work."
return render_template('errorHandler.html'), 404
首先,^{} “转储”到字符串,而不是文件。所以
将返回一个字符串,该字符串随后被绑定到} 来接受文件作为第二个参数。
save_article
变量,但文件实际上没有被修改。您可能打算使用^{注意:在Python 2中,file参数被忽略,我假设您正在使用它,因为它在Python 3中会显示为一个错误。
可能还有其他问题。一种是文章将附加到文件中,但代码的目的似乎是更新现有的文章。更新文本文件通常是不切实际的。一个更好的方法是遍历文章,更新与标题匹配的内容。然后在最后重写整个文件一次。下面是一个例子:
在更新项目数据时,您可能需要考虑使用一个简单的数据库来管理它。你可以看看Flask SQLAlchemy。
来自(http://blog.luisrei.com/articles/flaskrest.html)的示例
对于decorator中的每个方法,最好有一个if/elif/else,以防止出现奇怪的bug和边缘情况。
我认为你应该改变这部分:
为了更好的实践,我认为你应该:
或者将https方法分成不同的函数
相关问题 更多 >
编程相关推荐