Villahousut
Villahousut

Reputation: 135

How do I get the Flask package tutorial work with Poetry?

I'm using Poetry to manage my Python project (dependencies, package, etc) and I'm trying to implement the four-line hello world from Flask documentation: https://flask.palletsprojects.com/en/1.1.x/patterns/packages/#simple-packages

My folder structure looks like this:

myproject/
  .venv/
  myproject/
    __init__.py
    views.py
  poetry.lock
  pyproject.toml
  README.rst

The two files, __init__.py:

import myproject.views
__version__ = '0.1.0'

from flask import Flask
app = Flask(__name__)

And views.py:

from myproject import app

@app.route('/')
def index():
    return 'hello world'

Yet when I run export FLASK_APP=myproject and FLASK_ENV=development and do flask run, and point my browser to the port, it says

flask.cli.NoAppException
flask.cli.NoAppException: While importing "myproject", an ImportError was raised:

Traceback (most recent call last):
  File "/myproject/.venv/lib/python3.9/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
  File "/myproject/myproject/__init__.py", line 1, in <module>
    import myproject.views
  File "/myproject/myproject/views.py", line 1, in <module>
    from myproject import app
ImportError: cannot import name 'app' from partially initialized module 'myproject' (most likely due to a circular import) (/myproject/myproject/__init__.py)

How can I fix this? I'd like to use the recommended pattern.

Upvotes: 4

Views: 14353

Answers (2)

In your terminal, type poetry run flask run.

Upvotes: 10

Capi Etheriel
Capi Etheriel

Reputation: 3640

I believe your issue comes from importing the views at the top of __init__.py. Try moving the import statement to the end of the file, just like the tutorial does.

Upvotes: 2

Related Questions