2017-08-16 50 views
0

我正在使用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 
+0

你可以運行你的程序,並告訴我們你打印語句得到什麼,或者它甚至沒有編譯?我看到的一個簡單問題是,在第一種方法中,您將一些東西添加到從未聲明的變量「articles」中。 – JoshKopen

+0

文章是全球列表。上面的代碼不會顯示我所有的代碼。它運行沒有錯誤。然而問題是,當我用GET請求打開我的Json文件時,我只能打印整個對象,所以如果我添加了三篇文章,則會打印所有這些文章。我想只能打印這三篇文章中的一篇。我認爲你應該可以這樣做,只需寫入數據[「標題」](如果我想要標題)。但這不起作用,所以我認爲我添加文章的方式可能存在問題? –

回答

0

您的代碼問題來自您將return語句放在第一個代碼塊中的位置。當你做一個返回時,它立即結束你所在的方法,而不管它是否在循環中。你可能想嘗試這樣的東西,而不是:

@app.route('/api/articles', methods=['GET']) 
def show_articles(): 
    '''Opens dictionary and returns all users as json format''' 
    try: 
     with open('articles.json') as open_file: 
      json_ret = [jsonify({'article': article}) for article in open_file] 
      return json_ret 
    except: 
     return render_template('errorHandler.html'), 404 

這將會給你在我假設jsonified對象列表的形式是什麼你試圖做的最初。

+0

感謝您的快速回答!看到我上傳了錯誤的代碼,想要顯示發佈的請求。抱歉!但謝謝你發現我的錯誤。 :)你有什麼想法,爲什麼我不能看到只有一個對象,只有整個列表? –

+0

所有的好,都會試圖弄清楚這一點。 – JoshKopen