env.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from __future__ import with_statement
  2. from alembic import context
  3. from sqlalchemy import engine_from_config, pool
  4. from logging.config import fileConfig
  5. # this is the Alembic Config object, which provides
  6. # access to the values within the .ini file in use.
  7. config = context.config
  8. # Interpret the config file for Python logging.
  9. # This line sets up loggers basically.
  10. fileConfig(config.config_file_name)
  11. # add your model's MetaData object here
  12. # for 'autogenerate' support
  13. # from myapp import mymodel
  14. # target_metadata = mymodel.Base.metadata
  15. from flask import current_app
  16. config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI'))
  17. target_metadata = current_app.extensions['migrate'].db.metadata
  18. # other values from the config, defined by the needs of env.py,
  19. # can be acquired:
  20. # my_important_option = config.get_main_option("my_important_option")
  21. # ... etc.
  22. def run_migrations_offline():
  23. """Run migrations in 'offline' mode.
  24. This configures the context with just a URL
  25. and not an Engine, though an Engine is acceptable
  26. here as well. By skipping the Engine creation
  27. we don't even need a DBAPI to be available.
  28. Calls to context.execute() here emit the given string to the
  29. script output.
  30. """
  31. url = config.get_main_option("sqlalchemy.url")
  32. context.configure(url=url)
  33. with context.begin_transaction():
  34. context.run_migrations()
  35. def run_migrations_online():
  36. """Run migrations in 'online' mode.
  37. In this scenario we need to create an Engine
  38. and associate a connection with the context.
  39. """
  40. engine = engine_from_config(
  41. config.get_section(config.config_ini_section),
  42. prefix='sqlalchemy.',
  43. poolclass=pool.NullPool)
  44. connection = engine.connect()
  45. context.configure(
  46. connection=connection,
  47. target_metadata=target_metadata
  48. )
  49. try:
  50. with context.begin_transaction():
  51. context.run_migrations()
  52. finally:
  53. connection.close()
  54. if context.is_offline_mode():
  55. run_migrations_offline()
  56. else:
  57. run_migrations_online()