1

I have a flask app which uses a json file to store some config data. That .json file stores at the same location(directory) as the flask app file(app.py) is located. This flask app works fine in the local machine. But when I deploy to a live server (Ubuntu VPS), I'm getting a WSGI error says that

FileNotFoundError: [Errno 2] No such file or directory: 'config.json'

my code is for the .json file as follows

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
import json
import random

with open('config.json', 'r') as c:
    par = json.load(c)["par"]

What is the wrong with this and how to fix ?

azro
  • 53,056
  • 7
  • 34
  • 70
  • Are you sure you deployed the json file with the rest ? Try to `print(os.listdir('.'))` to see where you are – azro Jan 25 '20 at 15:31
  • server may run it in different folder, as different user, with different privileges - most for security reason. You may need to use full path to file. – furas Jan 25 '20 at 15:32
  • I tried with this. But same issue. json_data = os.path.join('config.json') with open(json_data, 'r') as c: par = json.load(c)["par"] – Thilina Wimalapriya Jan 25 '20 at 16:12

2 Answers2

1

This might help, change the name of your app.py to __init__.py or just create an empty __init__.py file in the same directory as your app.py file. There is plenty of explanation for this here:

What is __init__.py for?

  • did you try the full path to file? – David Witka Jan 25 '20 at 17:15
  • if you change the 'r' to an 'wb' run the code and then change it back to 'r' it will work, I know i tried it. – David Witka Jan 26 '20 at 06:12
  • it works after adding this: json_data = os.path.join('/var/www/webApp/webApp/config.json') with open(json_data, 'r') as c: par = json.load(c)["par"] But now I can't use the flask app inside my local computer. – Thilina Wimalapriya Jan 26 '20 at 06:41
  • Nothing worked. error log says '/config.json' not found. Then I renamed the file 'config.json' to '/config.json' using FileZilla. Then that file disappeared and the application (site) works fine. I don't know what happened. But now it works. – Thilina Wimalapriya Jan 26 '20 at 14:13
  • 1
    I recreated the problem again to see if I could get to the bottom of this. I'm using Visual Studio. The solution is this: the working directory of your terminal has to be the same as the directory your files are in. For instance my python file and config.json file are in C:\a\b\c\folder then I must run the python file when my terminal's working directory is also C:\a\b\c\folder. If you don't do this you get a file not found error. Please confirm and mark as solved. – David Witka Jan 26 '20 at 19:28
0

put that file in static directory Change path of file.

with open('static/config.json', 'r') as c:
    par = json.load(c)["par"]
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39