我正在使用Flask,Python 2.7和REST请求创建JSON API(保存在JSON文件中)。
我的问题是,我只能访问保存在JSON文件中的所有数据。我希望只能看到数组中的一个对象(当我想编辑数据,用于PUT请求时)和data ['title'],我现在不工作。这让我想,也许我没有正确保存请求的表单? 任何想法,当我用邮局保存数据是不正确的?或者如果还有其他问题? 感谢所有帮助!我的请求表单是否正确保存到JSON API中?
@app.route('/articleAdded', methods = ['POST'])
def added():
'''Adds new articles'''
if request.method == 'POST':
title = request.form['title']
author = request.form['author']
text = request.form['text']
article = {'title' : title, 'author' : author, 'text' : text}
articles.append(article)
try:
with open("articles.json", "w") as json_File:
new_art = json.dump(articles, json_File, sort_keys=True, indent=4)
json_File.close()
return render_template('articleAdded.html', title = title, author = author, text = text)
except:
return render_template('errorHandler.html'), 404
@app.route('/edit/<string:title>', methods=['GET'])
def edit(title):
'''shows specific aticle'''
try:
with open("articles.json", 'r') as article_file:
data = json.load(article_file)
print data['title']
if title == data['title'] :
print "hello"
return render_template('editArticle.html', data = data, title = title)
else:
print "Something went wrong!"
data.close()
except:
return render_template('errorHandler.html'), 404
你可以运行你的程序,并告诉我们你打印语句得到什么,或者它甚至没有编译?我看到的一个简单问题是,在第一种方法中,您将一些东西添加到从未声明的变量“articles”中。 – JoshKopen
文章是全球列表。上面的代码不会显示我所有的代码。它运行没有错误。然而问题是,当我用GET请求打开我的Json文件时,我只能打印整个对象,所以如果我添加了三篇文章,则会打印所有这些文章。我想只能打印这三篇文章中的一篇。我认为你应该可以这样做,只需写入数据[“标题”](如果我想要标题)。但这不起作用,所以我认为我添加文章的方式可能存在问题? –