2

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
2
  • 1
    Your question says you are working on a PUT request, but the code block is looking for a POST method. Commented Mar 4, 2018 at 7:44
  • I would get the error messages 500 and 404 if I put the PUT request in the if statement. Commented Mar 4, 2018 at 7:47

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

5 Comments

Could you show me an example how to update an article instead of the whole file?
@Angelica_92-: my point is that you need to rewrite the whole file because it is difficult to update a file in place. I have provided an example of how to do that above.
Thank you for the example! I can now change the value temporarily, however the change isn't saved.
What is articles['article']? Is it a list of dictionaries?
Yes exactly. Maybe I've done it wrong, but it is supposed to be a key value dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.