Search code examples
pythonjsonflaskpythonanywhere

Reading json in pythonanywhere flask app


First I have seen this question. My problem is I have a flask app running on pythonanywhere that reads info from a json file in the same directory on the server, and get the following error: Internal Server Error:The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application..

I simplified the app down to:

from flask import Flask
import json
app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    return 'Index'

@app.route('/courses')
def courses():
    with open('courses.json', 'r') as f:
        these_courses = json.load(f)
    return str(these_courses)

If I go to the index page I see index, as expected, but if I try to go to /courses then I get the error.The whole things runs fine on localhost, then with the same code I get an error on the server, so I know reading from the file works fine. This makes me think it might be a problem unique to json combined with pythonanywhere.

Edit: Perhaps a problem with the path name for courses.json, but it's in the same directory so I feel like it should be fine, just a thought


Solution

  • Turns out it was a pathname problem. I guess on files need to be routed from the root directory.

    I ran:

    def courses():
        my_dir = os.path.dirname(__file__)
        json_file_path = os.path.join(my_dir, 'courses.json')
        return json_file_path
    

    to find the path, then changed the function to:

    def courses():
        with open('/home/username/path/to/file/courses.json', 'r') as f:
            these_courses = json.load(f)
        return str(these_courses)
    

    and now it worked :D

    Then to make a better version that doesn't break when you move the project I did it like this:

    def courses():
        my_dir = os.path.dirname(__file__)
        json_file_path = os.path.join(my_dir, 'courses.json')
        with open(json_file_path, 'r') as f:
            these_courses = json.load(f)
        return str(these_courses)