我正在使用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文件時,我只能打印整個對象,所以如果我添加了三篇文章,則會打印所有這些文章。我想只能打印這三篇文章中的一篇。我認爲你應該可以這樣做,只需寫入數據[「標題」](如果我想要標題)。但這不起作用,所以我認爲我添加文章的方式可能存在問題? –