Is it possible to import variables from __init__.py in views.py? Is it possible to import variables from __init__.py in views.py? flask flask

Is it possible to import variables from __init__.py in views.py?


Try

import __init__VALUES = __init__.VALUES

from app import app, models, __init__ 

fails because you can not import from app if it is not in your scope.

from __init__ import VALUES

fails because VAULES is a variable and not a module/ function.

import VALUES

fails because, well... there is no VALUES module.


Try,

from app import VALUES

This might work.

If you want to do the data analysis only once in your application, give a read on these flask decorators,


No doubt this answer comes a bit late.

It also looks like the answer was found, but the reasons for it a little obscure, leaving room for some clarity as to how __init__.py can aid in organizing expansive projects, for one, by allowing modules within directories to discretize categories of functions (into modules) which can then be referenced through one name (the name of the folder the modules are in), leaving only remembering the names of functions in the bunch of files gathered in that folder, and properly importing them under that name.

Adding a couple of lines to __init__.py will configure it to expose the modules contained within the folder it naturally turns into a package, namely, in this case, the folder 'app'.

To __init__.py in the folder 'app', try adding:

from .models import <name of defs to expose>from .views import <name of defs to expose>

Then, in views.py, the module into which the imports should go, replace from app import app, models, __init__ with:

app import appfrom app import app <list of exposed fns needed here>

Instead of trying to import __init__.py anywhere, create a module within app which contains functions you want to expose through __init__.py to the rest of the application, using only the reference to 'app'.

Basically, all that happens here is the module names are made transparent and their exposed functions are grouped under the folder name. __init__.py makes this possible by turning the folder under which it exists into a package. That package can be put on the PYTHONPATH, or references to it within import statements can be done in pathname -relative, or -absolute fashion.