我试图弄清楚如何使用 Alembic 获取我的数据库版本。我已经将数据库设置为使用 alembic 并成功地对其进行了升级和降级。我现在想从我自己的 python 脚本中获取这个版本。
我试图为此创建一个函数
def get_current_database_version():
path = os.path.join(os.path.dirname(__file__), os.path.pardir)
alembic_cfg = Config(os.path.join(path, 'alembic.ini'))
current_rev = command.current(alembic_cfg, head_only=True)
return current_rev
该函数返回一个NoSectionError: No section: 'formatters'
然后我去我的 alembic.ini 文件检查它是否有一个格式化程序区域。这是我的 alembic.ini 文件:
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
pyramid_config_file = ../../development.ini
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# max length of characters to apply to the
# "slug" field
#truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
sqlalchemy.url = sqlite:///%(here)s/mgo.sqlite
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
有人知道我在做什么错吗?谢谢
编辑:
这是我尝试使用 MigrationContext 解决问题:
def get_database_revision():
engine = create_engine("sqlite:///../mgo.db")
conn = engine.connect()
context = MigrationContext.configure(conn)
current_rev = context.get_current_revision()
return current_rev
它连接但不返回。使用 sqlite 浏览器我可以看到数据库中的版本没有设置为无。