Confusion regarding Flask & importing modules Confusion regarding Flask & importing modules flask flask

Confusion regarding Flask & importing modules


You have to explicitly import app into your views file. The error says that app is not defined in views.py, that's because you need to do:

from steamapp import app

at the top of your views file.

The __init__.py turns your directory into a python package. At interpreter startup all the directories that are on $PYTHONPATH with __init__.py are added to sys.path which makes them importable. __init__.py is also executed when the module it defines is imported. This makes it extremely useful for e.g. exporting the main apis of your code. If you looked at the source code for flask you would see that all of the code that you do

from flask import Flask, request etc

is actually defined in smaller chunks of functionality in separate files and the interesting pieces are then exposed in __init__.py.

As said here Python doesn't want modules in packages to be the startup file. Python packaging is a bit of a mess. This stackoverflow answer helped me understand some of these questions, namely that relative imports break completely since they are calculated with respect __name__ which is set to '__main__' when you execute the file directly but the filename itself when it is used via import.

Aside from a few module level globals like __name__ and __package__ nothing is explicitly imported into the top level namespace. That's why app isn't available to you in your views.py file implicitly.

Does that answer your questions?

EDIT

You need to import views.py into __init__.py because otherwise your views.py file won't get executed and none of your routes and such will be defined. You need to import app into views.py because app isn't in the namespace that your views.py file is able to access. This pattern where two files import each other is called a circular import and can be tricky but it's fine here. You should know that after a module is loaded it gets cached so it doesn't get re-executed when it is imported again.

Your celery problem looks to me that python doesn't see your app on sys.path when celery is started. Showing the output of sys.path at that point would be helpful. My guess is if you add your working directory to $PYTHONPATH the issue will be fixed. When you install things with pip and the like the packages are added to a place where python knows how to find them by default.