Chet Meinzer
Chet Meinzer

Reputation: 1741

flask module import failure from test folder

How do I import modules located up (out of a test folder) and then back down my app folder structure?

in the app_test.py folder I want to

from app.models import User

running

/bin/python app_test.py

I get

no modules named app.models

I have an app_test.py file that worked until i did some shuffling, and now i'm not sure why My imports are not working when running tests from my test folder. I'm vitrualenv'd into my apps main folder and here's the basic layout minus superfluous folders/files:

/application

  /(leaving out folders bin build lib local...)
  /src
    /test
         __init__.py
         app_test.py
    /app 
         models.py
         forms.py
         __init__.py
         views.py
        /static
        /templates
        /tmp

What should my import be? I notice that the mega tutorial just uses a test.py file instead of a folder. is that the best way to do it, and if not, where should my test folder be located? It is driving me nuts.

Upvotes: 4

Views: 2936

Answers (1)

Ben Wilber
Ben Wilber

Reputation: 893

You either need to run your app_test.py from the top, (ie, "python test/app_test.py") or fixup the python path in app_test.py:

import os
import sys
topdir = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(topdir)

Upvotes: 10

Related Questions