Flask app was not getting SQLALCHEMY_DATABASE_URI value from .env in order to create tables in ProstgreSQL db.
Here's config:
import os
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = False
...
I tried
>>> from app.extensions import db
>>> db.create_all()
and
>>> from app import create_app
>>> app = create_app()
>>> from app.extensions import db
>>> db.create_all()
and
>>> from app import create_app
>>> app=create_app()
>>> app.app_context().push()
>>> from app.extensions import db
>>> db.create_all()
With a little help from my friends on Stackoverflow, I got to the working proc:
>>> from dotenv import load_dotenv
>>> load_dotenv()
>>> import os
>>> os.getenv('SQLALCHEMY_DATABASE_URI')
>>> from app import create_app
>>> app = create_app()
>>> app.app_context().push()
>>> from app.extensions import db
>>> db.create_all()
Question: Where is the bug? config.py
has import os
line. python_dotenv
is installed. What shall I do to avoid using the first four lines in the proc above?
Any help is greatly appreciated.
Until load_dotenv()
, whatever is in .env
is ignored. The question is where to do that load_dotenv()
. It has to happen before anyone reached in to os.environ
expecting something from .env
to be there.
The usually place, if you're following the pattern from the Flask Mega Tutorial, is right before
class Config(object):
E.g., https://github.com/miguelgrinberg/microblog/blob/v0.15/config.py