Issue
I created a Flask app for some of my projects. There is a main app.py in the ~/flasksvr
directory, and the folder structure looks a bit like this:
flasksvr/
> __init__.py (empty)
> app.py (main app)
> modules/ (subprojects)
> > __init__.py (empty)
> > subproj1.py
> > subproj2.py
> > subproj3.py
When I run app.py, it imports all the subprojects with URL prefixes like this:
from .modules.subproj1 import app as sp1app
from .modules.subproj2 import app as sp2app
from .modules.subproj3 import app as sp3app
app.register_blueprint(sp1app, url_prefix='/sp1')
app.register_blueprint(sp2app, url_prefix='/sp2')
app.register_blueprint(sp3app, url_prefix='/sp3')
Anyways, running it with flask run -h 0.0.0.0 --debug
works great, but when I run it with gunicorn app:app -b 0.0.0.0
, it gives me the error
from .modules.subproj1 import app as sp1app
ImportError: attempted relative import with no known parent package
I tried changing the from .modules.subproj1 import app as sp1app
part to from modules.subproj1 import app as sp1app
, and it worked. But in my subproject 1, I am importing a SocketIO app with from ..app import sock
(where sock
is sock = SocketIO(app, ping_interval=10)
in app.py). Then that gives me the error ImportError: Attempted relative import with no known parent package
. Why is this happening? Why does it work with regular Flask but not gunicorn? Using Python 3.9 on Debian 11.
Solution
With folder structure
flasksvr/
> __init__.py
> app.py <----- path is here
> modules/
> > __init__.py
> > subproj1.py <----- in this file subproj1.py is `from app import sock` because your root path now at app.py
> > subproj2.py
> > subproj3.py
When you run project in gunicorn, Gunicorn will load all resource to worker and the root path is at app.py gunicorn app:app
.It's different from running the flask run default, when call it will import
If you want to run both flask run and gunicorn. You can use:
flasksvr/
> app.py <------ from modules.subproj1 import app as sp1app
> modules/
> > subproj1.py <------ from app import sock
> > subproj2.py
> > subproj3.py
Answered By - TanThien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.