alembic апгрейд головы без выхода - PullRequest
0 голосов
/ 09 ноября 2018

У меня возникают проблемы при попытке обновить базу данных моего Flask API. Я хочу добавить новый столбец в таблицу "персоны".

У меня есть такая структура:

-- app
  -- alembic
    -- env.py
    -- README
    -- versions
      -- c12d697e5535_add_a_column.py
  -- common
    -- __init__.py
    -- base.py
  -- model
    -- Persons.py
    -- Teams.py
  -- __init__.py
  -- api.py

Это base.py :

# coding=utf-8

import os

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool

def get_engine():
    connection_string = os.environ['DATABASE_ENGINE'] + '://' + \
                        os.environ['DATABASE_USERNAME'] + ':' + \
                        os.environ['DATABASE_PASSWORD'] + '@' + \
                        os.environ['DATABASE_SERVER'] + '/dsiapi?charset=utf8'

    engine = create_engine(connection_string, pool_recycle=3600,  poolclass=QueuePool)
    return engine

engine = get_engine()
# use session_factory() to get a new Session
_SessionFactory = sessionmaker(bind=engine, autoflush=True, expire_on_commit = False)

Base = declarative_base()

def session_factory():
    Base.metadata.create_all(engine)
    return _SessionFactory()

def truncate_db():

    meta = MetaData(bind=engine, reflect=True)
    con = engine.connect()
    trans = con.begin()
    con.execute('SET FOREIGN_KEY_CHECKS = 0;')
    for table in meta.sorted_tables:
        con.execute(table.delete()) 
        con.execute("ALTER TABLE "+str(table)+" AUTO_INCREMENT = 1;")     
    con.execute('SET FOREIGN_KEY_CHECKS = 1;')
    trans.commit()

Это модель. Персоны .py :

# coding=utf-8

from sqlalchemy import Column, String, Date, Integer, Numeric, Enum
from common.base import Base
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import relationship, deferred
from model.DictSerializable import DictSerializable

class Persons( Base, DictSerializable ):
    __tablename__ = 'persons'

    id = Column( Integer, primary_key = True )
    name = Column( String )
    firstname = Column( String )
    lastname = Column( String )
    fonction = Column( String )
    organizations_id = Column( Integer, ForeignKey( "organizations.id" ), nullable = True )
    emails = Column( String )
    bitbucket_username = Column( String )


    persons_teams = relationship( "Teams", secondary = 'assoc_teams_persons', back_populates = 'teams_persons' )
    org = relationship( "Organizations", foreign_keys = [organizations_id] )

    def __init__( self, name, firstname, lastname, fonction, organizations_id, emails, bitbucket_username):
        self.name = name
        self.firstname = firstname
        self.lastname = lastname
        self.fonction = fonction
        self.organizations_id = organizations_id
        self.emails = emails
        self.bitbucket_username = bitbucket_username

Это env.py :

# imprt model.py
import os
import sys
MODEL_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")
sys.path.append(MODEL_PATH)
from model  import *
from common.base import Base

# edit this line and pass metadata
target_metadata = Base.metadata

это c12d697e5535_add_a_column.py :

"""Add a column

Revision ID: c12d697e5535
Revises: 20cc36b3a388
Create Date: 2018-11-08 16:14:17.219897

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'c12d697e5535'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    op.add_column('persons', sa.Column('iam_username', sa.String))

def downgrade():
    pass

Когда я бегу: alembic upgrade head Я ничего не получаю. столбец не добавлен. Я что-то здесь упускаю?

...