1

I am learning Flask. I found example with follow code

__init__.py:

from flask import Flask

app = Flask(__name__)
from app import views

view.py:

from app import app

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

and run.py (on top level):

from app import app
app.run()

I can't understand why I can't move from app import views to the top. If I do so I am getting error:

> run.py
Traceback (most recent call last):
  File "F:\app1\run.py", line 1, in <module>
    from app import app
  File "F:\app1\app\__init__.py", line 2, in <module>
    from app import views
  File "F:\app1\app\views.py", line 1, in <module>
    from app import app
ImportError: cannot import name 'app'
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145

2 Answers2

0

In run.py file line

from app import app

means "from package app (folder with __init__.py file, F:\app1\app in your case, import object app", and in __init__.py file line

app = Flask(__name__)

creates an application object. Main confusion caused by your application name - app - which coincides with application object name.
If you move line

from app import views

above

app = Flask(__name__)

from app import app in view.py will raise ImportError, because object app from app package not defined yet.

kvorobiev
  • 5,012
  • 4
  • 29
  • 35
0

Python is interpreted language. When it comes to one line it try to execute it. And that is why you cannot import views before defining app.

Working version of __init__.py

app = Flask(__name__)
from app import views # it will "execute: views.py"
# views.py - indenting for better understanding
    from app import app # App is defined here and it can be imported

Not working version of __init__.py

from app import vies # it will execute vies.py"
# vies.py - indenting for better understanding
    from app import app # Exception - app doesn't exist here
app = Flask(__name__)

You need to be really careful with python imports.