Launch Flask app factory (with create_app()) from external file

Issue

Following this tutorial to dockerize a Flask stack, I am trying to lauch an existing application from an external manage.py file

My app structure goes like:

└── services
    └── web
        ├── manage.py
        └── myapp
            └── requirements.txt
            └── myserver
                └──__init__.py
                └──config
                   └──config.py

The manage.py file:

import os
os.chdir('myapp')
from flask.cli import FlaskGroup
from myapp.myserver import create_app

app = create_app()

cli = FlaskGroup(app)


if __name__ == "__main__":
    cli()

and finally, the myapp/myserver/__init__.py file (simplified):

from myserver.config.config import Config # this file exists and imports work when i launch from pycharm 

def create_app():
    app = Flask(__name__)
    ...other stuff here
    return app

So when I try to run: python3 manage.py run, the ouput goes:

  File "manage.py", line 4, in <module>
    from myapp.myserver import create_app
  File "/var/www/html/flask-docker/services/web/myapp/myserver/__init__.py", line 12, in <module>
    from myserver.config.config import Config

The config import from __init__.py cannot be resolved. I tried to solve this with the chdir visible in manage.py.

My env variables are the one I got from a working Pycharm flask setup :

FLASK_APP="myserver:create_app()"

I managed to sucessfully pass the import instruction by replacing :

from myserver.config.config import Config

by

from .config.config import Config

but the whole project contains imports beginning by from myserver

So the final question is: why the init file inside myserver does not recognize myserver folder/module ? This setup works just fine when I laucnh it via PyCharm

Solution

Brandons comment and this answer led me to a solution

manage.py

import sys
#this is the fix
sys.path.append(os.path.join(os.path.dirname(__file__),'myapp'))
from flask.cli import FlaskGroup
from myapp.myserver import create_app

app = create_app()

cli = FlaskGroup(app)
## Heading ##
if __name__ == "__main__":
    cli()

Instead of changing the working directory with os.chdir, I change it using sys.path. I am now able to use my servers init file

Answered By – tbarbot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published