Proper way to import modules and run flask app

I have a flask application that I am running. I am currently running the app as a python script using flasks command app.run()

The script currently looks like


from src.pkg1 import func1
from src.pkg2 import func2

app = flask.Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return('Hello world')

if __name__ == '__main__':
    app.run()

This works great when running this app.py file as a python script.

the file structure is the root repository directory contains a src folder with all the code that needs to be run. However the problem is that when I try to run the app using flask run I get an error.

if i cd into the src folder and run flask run the output i get is

Error: While importing "repo.src.app", an ImportError was raised:

Traceback (most recent call last):
  File "d:\folder\repo\venv\lib\site-packages\flask\cli.py", line 240, in locate_app
    __import__(module_name)
  File "D:\folder\repo\src\app.py", line 3, in <module>
    from src.pkg1 import func1
ModuleNotFoundError: No module named 'src'

I can solve this problem by changin the imports to relative like so


from .pkg1 import func1
from .pkg2 import func2

app = flask.Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return('Hello world')

if __name__ == '__main__':
    app.run()

But then running the app as a python script wont work and the output is

Traceback (most recent call last):
  File "D:/folder/repo/src/app.py", line 3, in <module>
    from .pkg1 import func1
ModuleNotFoundError: No module named '__main__.pkg1'; '__main__' is not a package

Why is this happening and how can I fix this? Why does running flask run treat the app differently. What is the expected use for relative and absolute imports?

Any help is appreciated.

Thank you!



from Recent Questions - Stack Overflow https://ift.tt/34zpMDV
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation