8

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.

Community
  • 1
  • 1
Pav Sidhu
  • 6,724
  • 18
  • 55
  • 110

1 Answers1

8

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?

Martin
  • 967
  • 1
  • 6
  • 17
  • I did have the `__init__.py` in the views folder, just forgot to include it in the question, I just updated it. I tried using `from .. import db` but got the same error. – Pav Sidhu Aug 02 '15 at 17:14
  • Sorry but I'm relatively new to creating packages with python. Would the package name just be the root folder that `__init__.py` is in? – Pav Sidhu Aug 02 '15 at 23:59
  • Ah, yes, my bad. I should have said app, not package. – Martin Aug 03 '15 at 04:38
  • Just to clarify, the `.` means current package; and the two dots mean "one package above" (they don't refer to file names); from [pep-0328](https://www.python.org/dev/peps/pep-0328/): _"Two or more leading dots give a relative import to the parent(s) of the current package, one level per dot after the first."_ - except in the special case of `__init__.py` – Burhan Khalid Aug 03 '15 at 04:53