2017-08-16 39 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