Question

Use case:

I'm attempting to create a migration script that will create a table (which will make a many to many relationship) and then populate that table with foreign keys from the database.

To do this I'm attempting to load my flask applications ORM models so that I may use them in my migration script.

directory structure

/home/alord/git/my_project/  #  project directory
/home/alord/git/my_project/alembic_testing  #  migration directory
/home/alord/git/my_project/my_project #requirement of flask modules
/home/alord/git/my_project/runserver.py  #  script that starts development server
/home/alord/git/my_project/alembic.ini  #  alembic configuration
/home/alord/git/my_project/development_config.py  #  development server configuration

if I run alembic upgrade +1

import os
print os.getcwd()
print os.path.dirname(os.path.realpath(__file__))

in

/home/alord/git/my_project/alembic_testing/env.py

I get

/home/alord/git/my_project
/home/alord/git/my_project/alembic_testing

What I'm doing

I'm placing

import os.path
sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import my_project

In my upgrade script and then running the command

alembic upgrade +1

and I'm recieving a stack trace with the error

ImportError: No module named my_project

Without this attempted import the table upgrade and downgrade functions run without error.

What I expect

I would like to be able to import the package, and more importantly *my_project.models* so that I can use the ORM to populate my new table.

Note: I can't use relative package inclusion because I'm running alembic rather than calling python. As such, the python -m argument isn't useful to me.

Was it helpful?

Solution 2

Short answer:

trying to inport from a revision file in alembic puts you two directories down instead of one.

Long answer:

So I ended up printing off my sys.path to see what directories were actually included. When I noticed that the path that was included was

/home/alord/git/my_project/alembic_testing

instead of

/home/alord/git/my_project/alembic_testing

I made my path.append go up one more directory using,

import sys
import os.path

#hacky solution to get to the root application directory.
sys.path.append(
        os.path.abspath(
            os.path.join(
                os.path.join(
                    os.path.dirname(__file__),
                    os.path.pardir),
                os.path.pardir)))

OTHER TIPS

Fix your script_location in alembic.ini to point to the right place, then just run alembic from the root of your repository (/home/alord/git/), and you shouldn't need any sys.path hijinks to be able to import your app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top