Python 3 - Cannot make relative imports to flask server application created in virtualenv -
i set flask_app
api.py
, run flask run
, receive error systemerror: parent module '' not loaded, cannot perform relative import
. there's no error on pycharm whatsoever, confirms syntactically correct.
api.pi
from . import models flask import flask app = flask(__name__) @app.route('/') def hello_world(): return 'hello, welcome api!' if __name__ == '__main__': app.run()
the directory structure
├── projectdirectory │ ├── flask-api │ │ ├── venv │ │ ├── api.py │ │ └── models.py │ ├── modelpackage │ │ ├── __init__.py │ │ ├── classa.py │ │ ├── classb.py │ │ ├── helpers.py │ │ └── simplescript.py
as can see above, both api.py
, models.py
in same directory, , using from . import models
line should import script's code api.py
. reference, flask server made using virtualenv
, following official flask docs, hence there venv
directory in flask-api
directory.
also, models.py
further imports stuff modelpackage
, that's why included above completeness.
does have flask/virtualenv/directory structure?
when module used main name __main__
. , relative imports not work. should use absolute imports. i.e from flask_api import models
here link more info documentation
note relative imports based on name of current module. since name of main module "main", modules intended use main module of python application must use absolute imports.
note: according pep8 use absolute imports rather relative ones.
Comments
Post a Comment