Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import from __init__.py with Flask

I have the following file structure for a Flask application:

myapplication/
  run.py
  myapplication/
    __init__.py
    views/
      __init__.py
      models.py
      ...
    templates/
    static/

And I have initialised the database in myapplication/__init__.py using SQLAlchemy. I want to import the database object in models.py though I'm unsure on how to do it.

I read this answer and tried to import the database object from myapplication/__init__.py using relative imports like this:

from ... import db

but I receive this error: ValueError: Attempted relative import in non-package.

So how to I get to the database object in myapplication/__init__.py for models.py? Thanks.

like image 253
Pav Sidhu Avatar asked Aug 02 '15 17:08

Pav Sidhu


People also ask

Can I import from __ init __ py?

To do so, we can either use relative or absolute import within __init__.py (or set the PYTHONPATH variable as described above). Relative imports (not recommended): specify the path relative to the path of the calling script. We use the dot notation( . or .. ) in specifying relative imports.

What is __ init __ py in flask?

Files named __init__.py are used to mark directories on disk as Python package directories. So it really depends on your structure of projects. Ideally if you have a project with multiple folders, you might have to make them as python package directories.

How do I import a module into a flask?

the Flask application object creation has to be in the __init__.py file. That way each module can import it safely and the __name__ variable will resolve to the correct package. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__.py file.

How is __ init __ py used?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.


1 Answers

Add an empty file called __init__.py to your views folder. Also, I think you have a dot too many, i.e. it should be from .. import db. The first . references views and the second . will reference your __init__.py.

EDIT: I had a look at the flask stuff I did myself (freevle), and it seems like I never used a relative import to get at the database. In stead I used the app name, i.e. the name of the folder your top __init__.py is in. With freevle, I used from freevle import db. Would this work for you?

like image 135
Martin Avatar answered Sep 30 '22 15:09

Martin