Mike Resoli Mike Resoli - 1 year ago 138
JSON Question

Reading a .json file using python - Flask

I'm trying to read a

file from within my Flask application using:

def renderblog():
with open(url_for("static", filename="blogs.json")) as blog_file:
data = json.load(blog_file)

However I get the error:

FileNotFoundError: [Errno 2] No such file or directory: '/static/blogs.json'

Now I know for a fact that the directory exists within my project structure, but I have no idea why I'm getting this error. Any ideas? Is there a specific way to retrieve
in Flask?

Answer Source

You generated a URL path, not a path to the local static folder. Use the app.static_folder attribute instead:

def renderblog():
    filename = os.path.join(app.static_folder, 'blogs.json')
    with open(filename) as blog_file:
        data = json.load(blog_file)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download