本文介绍了Alembic - sqlalchemy初始迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个初始迁移时遇到问题,它会自动使用我在models.py中定义的表,方法是使用共享的Base(declarative_base)。



当我输入命令:

  alembic revision --autogenerate 

alembic创建一个空文件。



我的配置或我的方法有什么问题?



project.base.py:

 从sqlalchemy.ext.declarative import declarative_base 


Base = declarative_base()

env.py:

  import sys 
import os

sys.path.append(os.path.abspath(os .getcwd()))
from alembic import context
from sqlalchemy import engine_from_config,pool
from logging.config import fileConfig

from project.base import Base
target_metadata = Base.metadata
def run_migrations_online():
以在线模式运行迁移

在这种情况下,我们需要创建一个Engine
并将连接与上下文相关联。


engine = engine_from_config(
config.get_section(config.config_ini_section),
prefix ='sqlalchemy。',
poolclass = pool .NullPool)

connection = engine.connect()
context.configure(
connection = connection,
target_metadata = target_metadata


#target_metadata.reflect(engine,only = [
#django_migrations,
#auth_group_permissions,
#django_session,
#auth_user_user_permissions
#auth_user_groups,
#django_admin_log,
#auth_permission,
#auth_user,
#sysdiagrams,
# django_content_type,
#auth_group,
#sysdiagrams,
#])

try:
with context.begin_transaction()
context.run_migrations()
finally:
connection.close( )


如果context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

示例模型:

 # -  *  - 编码:utf-8  -  *  -  

从sqlalchemy导入列,整数,字符串,DateTime,布尔值,ForeignKey,SmallInteger
从sqlalchemy.orm导入关系,backref
从项目.base import Base


__schema__ =用户


类用户(基数):
__tablename__ =用户
__table_args__ = {'schema':__schema__}

USER_CUSTOMER = 0
USER_EMPLOYEE = 5
USER_ADMIN = 10

USER_TYPES =(
(USER_CUSTOMER,U'Klient'),
(USER_EMPLOYEE,u'Obsługasklepu'),
(USER_ADMIN,u'Administrator')


id = Column(Integer,primary_key = True)
name =列(String(255))
email =列(String(255))
password = mn(String)
date_created =列(DateTime)
date_updated =列(DateTime)
user_type =列(SmallInteger)

is_active =列(布尔)

def __repr __(self):
return u< User:({} {})>。format(self.id,self.name)

def is_management(self):
返回self.user_type在[self.USER_EMPLOYEE,self.USER_ADMIN]

def is_admin(self):
return self.user_type == self .USER_ADMIN

编辑:



ve发现Base.metadata.sorted_tables是空的。

解决方案

除了导入声明性的 Base class,您还需要导入所有的模型。像 import project.models 或者你必须包括的任何模块,以便导入所有的模型类。否则,您的 Base.metadata 不会填充您的模型定义,因为 env.py 从不包含它们。 / p>

I am having a problem creating an initial migration which would automatically have tables that I've defined in my models.py by using shared Base (declarative_base).

When I enter a command:

alembic revision --autogenerate

alembic creates an empty file.

What's wrong in my configs or my approach?

project.base.py:

from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

env.py:

import sys
import os

sys.path.append(os.path.abspath(os.getcwd()))
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig

from project.base import Base
target_metadata = Base.metadata
def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    engine = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    connection = engine.connect()
    context.configure(
        connection=connection,
        target_metadata=target_metadata
    )

    # target_metadata.reflect(engine, only=[
    #     "django_migrations",
    #     "auth_group_permissions",
    #     "django_session",
    #     "auth_user_user_permissions",
    #     "auth_user_groups",
    #     "django_admin_log",
    #     "auth_permission",
    #     "auth_user",
    #     "sysdiagrams",
    #     "django_content_type",
    #     "auth_group",
    #     "sysdiagrams",
    # ])

    try:
        with context.begin_transaction():
            context.run_migrations()
    finally:
        connection.close()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

Sample model:

# -*- coding: utf-8 -*-

from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, SmallInteger
from sqlalchemy.orm import relationship, backref
from project.base import Base


__schema__ = "Users"


class User(Base):
    __tablename__ = "User"
    __table_args__ = {'schema': __schema__}

    USER_CUSTOMER = 0
    USER_EMPLOYEE = 5
    USER_ADMIN = 10

    USER_TYPES = (
        (USER_CUSTOMER, u'Klient'),
        (USER_EMPLOYEE, u'Obsługa sklepu'),
        (USER_ADMIN, u'Administrator')
    )

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    email = Column(String(255))
    password = Column(String)
    date_created = Column(DateTime)
    date_updated = Column(DateTime)
    user_type = Column(SmallInteger)

    is_active = Column(Boolean)

    def __repr__(self):
        return u"<User: ({} {})>".format(self.id, self.name)

    def is_management(self):
        return self.user_type in [self.USER_EMPLOYEE, self.USER_ADMIN]

    def is_admin(self):
        return self.user_type == self.USER_ADMIN

Edit:

I've discovered that Base.metadata.sorted_tables is empty.

解决方案

In addition to importing your declarative Base class, you also need to import all of your models as well. Something like import project.models or whatever module(s) you have to include so that all your model classes are imported. Otherwise, your Base.metadata doesn't get populated with your model definitions since env.py never includes them.

这篇关于Alembic - sqlalchemy初始迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:44