Dakkar
Dakkar

Reputation: 5952

How to use flask configuration in instance folder and basedir

I have the following flask app:

main.py

from application import create_app    
app = create_app('flask.cfg')

application/init.py

def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile(config_filename)

instance/flask.cfg

import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = os.environ.get(
    'DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'database/app.db')

My problem with this setup: basedir resolves to the instance folder and not to the basedir of my project where my database folder is located. Whats the best way to handle this?

Upvotes: 2

Views: 5565

Answers (1)

DarkSuniuM
DarkSuniuM

Reputation: 2582

__file__ is the same directory that your file is in.

You used __file__ in instance/flask.cfg so it refers to instance/ where flask.cfg is!

All you need is going one step back to your project directory cause your main.py is in the project directory

You need to do something like this:

basedir = os.path.abspath(os.path.join('../', os.path.dirname(__file__)))

Also this will work

basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Upvotes: 4

Related Questions