Pav Sidhu
Pav Sidhu

Reputation: 6944

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.

Upvotes: 8

Views: 7732

Answers (1)

Martin
Martin

Reputation: 1069

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?

Upvotes: 8

Related Questions