Put request python flask

a 夏天 提交于 2019-12-08 14:09:00

问题


I'm working on a PUT request to be able to modify data in my JSON file, using Flask and Python. The problem is it won't save the changes made.

Below is my code:

@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

回答1:


I think you should change this part:

if request.method == 'POST' or request.method == 'PUT':

For better practices, i think you should do:

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

Or separate your https methods into different functions




回答2:


Example from (http://blog.luisrei.com/articles/flaskrest.html)

@app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
    if request.method == 'GET':
        return "ECHO: GET\n"

    elif request.method == 'POST':
        return "ECHO: POST\n"

    elif request.method == 'PATCH':
        return "ECHO: PACTH\n"

    elif request.method == 'PUT':
        return "ECHO: PUT\n"

    elif request.method == 'DELETE':
        return "ECHO: DELETE"

Probably best to have a if/elif/else for each method in the decorator, prevents weird bug and edge cases.




回答3:


First of all, json.dumps() "dumps" to a string, not a file. So

save_article = json.dumps(article, json_File)

will return a string which is then bound to the save_article variable, but the file is not actually modified. You probably meant to use json.dump(article, json_File) which does accept a file as the second argument.

Note: The file argument is silently ignored in Python 2, which I assume that you are using because it would show up as an error in Python 3.


There might be other problems. One is that articles will be appended to the file, but it would seem that the intention of the code is to update an existing article. It's generally impractical to update text files in place. A better method would be to iterate over the articles, updating those that match the title. Then rewrite the whole file once at the end. Here's an example:

        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)

As you are updating the article data you might want to consider using a simple database to manage it. You could take a look at Flask SQLAlchemy.



来源:https://stackoverflow.com/questions/49093115/put-request-python-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!