Joey Jiao
Joey Jiao

Reputation: 91

Read and write json files to server with flask

I need a json file on the server to store some data, but it won't be too big to need a database. So I try to read the file, and after I finish using it I will need to overwrite the data to keep update. I tried like this:

@app.route("/json")
def readwrite():
    SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
    json_url = os.path.join(SITE_ROOT,'static', 'test.json')
    token = open(json_url)
    return token

But I get a 404 error on those. I'm not sure how I can read out those data and further rewrite. Please help if you see any problem in my code. Thanks!

Upvotes: 0

Views: 3376

Answers (1)

Bennett Brown
Bennett Brown

Reputation: 5383

You are returning the file handle via HTTP to the client. Get the json data and send that.

stored_json = token.readlines()
token.close()
return stored_json

Upvotes: 1

Related Questions