Я столкнулся с проблемой при использовании flask-sqlalchemy внутри контейнера докера.Если я выполняю команду db init
из Flask-Script Manager, файл /migrations
не создается, однако, если я docker exec -it bash
в контейнер и запускаю ту же команду, создается каталог /migrations
.Не уверен, почему это есть у кого-нибудь по этому поводу?Необходимость выполнять exec в контейнер каждый раз быстро стареет.
Я начал работать над этим учебником https://realpython.com/dockerizing-flask-with-compose-and-machine-from-localhost-to-the-cloud/
Это код для manage.py
from flask_script import Manager, Command, Option
from flask_migrate import Migrate, MigrateCommand
from project.Models import *
from project.config import BaseConfig
from project.app import app, db
from project.utilities import users
from os import environ
from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
migrate = Migrate(app, db)
manager = Manager(app)
class DropAll(Command):
def run(self):
if environ["STAGE"] == "DEV":
SQLALCHEMY_DATABASE_URI = 'postgresql://{0}:{1}@{2}:{3}/'.format(
BaseConfig.DB_USER, BaseConfig.DB_PASS, BaseConfig.DB_SERVICE, BaseConfig.DB_PORT
)
con = connect(SQLALCHEMY_DATABASE_URI)
cursor = con.cursor()
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor.execute("DROP DATABASE {}".format(environ["DB_NAME"]))
con.close()
else:
print("You need to be in a DEV environment to drop the database willy nilly")
class CreateDB(Command):
def run(self):
SQLALCHEMY_DATABASE_URI = 'postgresql://{0}:{1}@{2}:{3}/{4}'.format(
BaseConfig.DB_USER, BaseConfig.DB_PASS, BaseConfig.DB_SERVICE, BaseConfig.DB_PORT, "postgres"
)
con = connect(SQLALCHEMY_DATABASE_URI)
cursor = con.cursor()
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor.execute("CREATE DATABASE {}".format(environ["DB_NAME"]))
con.close()
class CreateAppAdmin(Command):
option_list = (
Option('--name', '-n', dest='username'),
Option('--password', "-p", dest="password"),
Option('--fname', "-fn", dest="f_name"),
Option('--lname', "-ln", dest="l_name"),
Option('--phone', "-pn", dest="phone"),
Option('--dob', dest="dob")
)
def run(self, username, password, f_name, l_name, phone, dob):
print("Hello friend lets set this admin account up for you")
users.create_user(username, password, f_name, l_name, phone, dob)
print("that account is setup for you")
manager.add_command('db', MigrateCommand)
manager.add_command("create_app_admin", CreateAppAdmin())
manager.add_command("drop_db", DropAll())
manager.add_command("create_db", CreateDB())
if __name__ == '__main__':
manager.run()
Консольный вывод
Users-MacBook-Pro:roots user$ docker-compose up --build -d
Building web
Step 1/7 : FROM python:3.7-slim
---> b5a7c089ece3
Step 2/7 : RUN python3 -m pip install -U pip setuptools
---> Using cache
---> e502e3ae5158
Step 3/7 : COPY requirements.txt requirements.txt
---> Using cache
---> 7ab95a90e368
Step 4/7 : RUN python3 -m pip install -r ./requirements.txt
---> Using cache
---> 98b9c90091fc
Step 5/7 : RUN mkdir ./project
---> Using cache
---> ce33119d9696
Step 6/7 : COPY . ./project
---> Using cache
---> ae17a52c8436
Step 7/7 : ENV PYTHONPATH "${PYTHONPATH}:/project"
---> Using cache
---> ee25162063d7
Successfully built ee25162063d7
Successfully tagged roots_web:latest
Building nginx
Step 1/3 : FROM tutum/nginx
---> a2e9b71ed366
Step 2/3 : RUN rm /etc/nginx/sites-enabled/default
---> Using cache
---> 33de550613f7
Step 3/3 : COPY sites-enabled/ /etc/nginx/sites-enabled
---> Using cache
---> 14cc2d960b56
Successfully built 14cc2d960b56
Successfully tagged roots_nginx:latest
Starting roots_data_1 ...
Starting roots_data_1 ... done
Recreating roots_web_1 ... done
Recreating roots_nginx_1 ... done
Users-MacBook-Pro:roots user$ docker-compose run web /usr/local/bin/python /project/management_scripts/manage.py create_db
Starting roots_postgres_1 ... done
/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Users-MacBook-Pro:roots user$ docker-compose run web /usr/local/bin/python /project/management_scripts/manage.py db init
Starting roots_postgres_1 ... done
/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Creating directory /migrations ... done
Creating directory /migrations/versions ... done
Generating /migrations/script.py.mako ... done
Generating /migrations/env.py ... done
Generating /migrations/alembic.ini ... done
Generating /migrations/README ... done
Please edit configuration/connection/logging settings in '/migrations/alembic.ini' before proceeding.
Users-MacBook-Pro:roots user$ docker-compose run web /usr/local/bin/python /project/management_scripts/manage.py db migrate
Starting roots_postgres_1 ... done
/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Error: Path doesn't exist: 'migrations'. Please use the 'init' command to create a new scripts folder.
Users-MacBook-Pro:roots user$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
14c78cdd5a07 roots_nginx "/usr/sbin/nginx" About a minute ago Up About a minute 0.0.0.0:80->80/tcp roots_nginx_1
19081a44984c roots_web "usr/local/bin/gunic…" About a minute ago Up About a minute 8000/tcp roots_web_1
4cacce25bc7e postgres:latest "docker-entrypoint.s…" 34 hours ago Up 34 hours 0.0.0.0:5432->5432/tcp roots_postgres_1
Users-MacBook-Pro:roots user$ docker exec -it 19081a44984c bash
root@19081a44984c:/# ls
bin boot dev etc home lib lib64 media mnt opt proc requirements.txt root project run sbin srv sys tmp usr var
root@19081a44984c:/# python project/management_scripts/manage.py db init
/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Creating directory /migrations ... done
Creating directory /migrations/versions ... done
Generating /migrations/script.py.mako ... done
Generating /migrations/env.py ... done
Generating /migrations/alembic.ini ... done
Generating /migrations/README ... done
Please edit configuration/connection/logging settings in '/migrations/alembic.ini' before proceeding.
root@19081a44984c:/# ls
bin boot dev etc home lib lib64 media migrations mnt opt proc requirements.txt root project run sbin srv sys tmp usr var
root@19081a44984c:/# python project/management_scripts/manage.py db migrate
/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
INFO [alembic.autogenerate.compare] Detected added table 'User'
INFO [alembic.autogenerate.compare] Detected added table 'AppAdmins'
INFO [alembic.autogenerate.compare] Detected added table 'Password'
INFO [alembic.autogenerate.compare] Detected added table 'Session'
Generating /migrations/versions/a1363884c221_.py ... done
root@19081a44984c:/#