将请求放入python烧瓶
我正在处理一个PUT请求,以便能够使用Flask和Python修改JSON文件中的数据。问题是它不会保存所做的更改 下面是我的代码:将请求放入python烧瓶,python,json,flask,put,Python,Json,Flask,Put,我正在处理一个PUT请求,以便能够使用Flask和Python修改JSON文件中的数据。问题是它不会保存所做的更改 下面是我的代码: @app.route('/updated', methods = ['POST', 'PUT' 'GET']) def update(): try: title = request.form['title'] print title if request.method == 'POST':
@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
我认为你应该改变这一部分:
if request.method == 'POST' or request.method == 'PUT':
为了获得更好的实践,我认为您应该:
if request.method == 'POST' or request.method == 'PUT':
# do your code here, which edit into your database
if request.method == 'GET':
# do GET code here, which return data from your database
或者将https方法分成不同的函数,例如
对于decorator中的每个方法,最好都有一个if/elif/else,以防止出现奇怪的bug和边缘情况 首先,转储到字符串,而不是文件。所以
save_article = json.dumps(article, json_File)
将返回一个字符串,该字符串随后绑定到save_article变量,但该文件实际上未被修改。您可能想使用哪个接受文件作为第二个参数
注意:文件参数在Python2中被默默地忽略,我假设您正在使用它,因为它在Python3中会显示为错误
可能还有其他问题。一种是,文章将被附加到文件中,但代码的目的似乎是更新现有的文章。在适当的位置更新文本文件通常是不切实际的。更好的方法是迭代文章,更新与标题匹配的文章。然后在最后重写整个文件一次。下面是一个例子:
with open("articles.json", 'r') as json_File:
articles = json.load(json_File)
# update any matching articles
for article in articles['article']:
if title == article['title']:
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
# rewrite the whole JSON file with updated dictionary
with open("articles.json", 'w') as json_File:
json.dump(articles, json_File)
当您正在更新文章数据时,您可能需要考虑使用一个简单的数据库来管理它。你可以看看 你的问题是你正在处理一个PUT请求,但是代码块正在寻找POST方法。如果我将put请求放在if语句中,我会得到错误消息500和404。你能给我举个例子说明如何更新文章而不是整个文件吗?@Angelica_92-:我的观点是,你需要重写整个文件,因为很难在适当的位置更新文件。我已经提供了一个如何做到这一点的例子上面。谢谢你的例子!我现在可以临时更改该值,但是更改不会保存。什么是articles['article']?这是一份字典清单吗?是的,没错。也许我做错了,但它应该是一个键值字典。
with open("articles.json", 'r') as json_File:
articles = json.load(json_File)
# update any matching articles
for article in articles['article']:
if title == article['title']:
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
# rewrite the whole JSON file with updated dictionary
with open("articles.json", 'w') as json_File:
json.dump(articles, json_File)