2

I have a few functions in my Alembic migrations that tend to be used in multiple revision scripts (for example, adding creation/updated timestamps to a table). I'd like to not need to copy-paste the same function over and over, but I've been having trouble importing a module from inside the revision script.

Project directory structure looks like:

app/
    __init__.py
    main.py
alembic/
    env.py
    versions/
        xxx_revision.py
tests/
    test_stuff.py

I've tried putting __init__.py in the alembic directory and putting a lib.py there, but relative imports didn't work. I also tried putting the lib.py in the alembic/versions/ directory, but alembic complains that it's not a revision file.

pipai
  • 21
  • 2

1 Answers1

1

I needed the same thing. So in the end I found this solution:

  1. Add python file alembic_utils.py to app directory (with your function - some_function)

  2. In your xxx_revision.py put this:


import os
import sys
PACKAGE_PARENT = '../..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(),os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

and also add import:

from app.alembic_utils import some_function