Я установил необходимые пакеты в виртуальной среде, созданной с помощью Python 3.5.
virtualenv -p python3 venv --no-site-packages
source venv/bin/activate
pip install flask
pip install Flask-SQLAlchemy
pip install Flask-Migrate
pip freeze>requirements.txt
requirements.txt
:
alembic==1.0.8
Click==7.0
Flask==1.0.2
Flask-Migrate==2.4.0
Flask-SQLAlchemy==2.3.2
itsdangerous==1.1.0
Jinja2==2.10.1
Mako==1.0.8
MarkupSafe==1.1.1
python-dateutil==2.8.0
python-editor==1.0.4
six==1.12.0
SQLAlchemy==1.3.2
Werkzeug==0.15.2
Поскольку flask-migrate
ищет app.py
при запуске flask db init
, я переименовал Basic.py
в app.py
.
Я запустил присоединенный setupdatabase.py
для создания базы данных SQLite и crud.py
для создания фиктивных записей.
Я создал маршрут, чтобы проверить, передаются ли эти данные SQLite в шаблон Flask.
обновлено app.py
:
__author__ = 'User'
import os
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class Puppy(db.Model):
__tablename__ = 'puppies'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
age = db.Column(db.Integer)
def __init__(self,name,age):
self.name = name
self.age = age
def __repr__(self):
return "Puppy {} is {} year/s old".format(self.name, self.age)
@app.route('/')
def home():
data = Puppy.query.all()
return render_template("home.html", data = data)
if __name__ == '__main__':
app.run(debug=True)
home.html
<html>
<head>
<title>Home</title>
</head>
<body>
<h3>Puppies</h3>
<div>{{ data }}</div>
</body>
</html>
Данные передаются в шаблон:
Затем я выполнил команду init
, migrate
и upgrade
, как указано в официальной документации по flask-migrate .
(venv) ➜ flask db init
/home/.../flask_data_migration/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:794: 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
/home/.../flask_data_migration/migrations ... done
Creating directory
/home/.../flask_data_migration/migrations/versions
... done
Generating
/home/.../flask_data_migration/migrations/env.py ... done
Generating
/home/.../flask_data_migration/migrations/README ... done
Generating /home/.../flask_data_migration/migrations
/script.py.mako ... done
Generating /home/.../flask_data_migration/migrations
/alembic.ini ... done
Please edit configuration/connection/logging settings in '/home/.../flask_data_migration/migrations/alembic.ini' before proceeding.
(venv) ➜ flask db migrate
/home/.../flask_data_migration/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:794: 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 SQLiteImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.env] No changes in schema detected.
(venv) ➜ flask db upgrade
/home/.../flask_data_migration/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:794: 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 SQLiteImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
Структура каталогов после выполнения миграций (пропущенная папка venv):
.
├── app.py
├── crud.py
├── data.sqlite
├── migrations
│ ├── alembic.ini
│ ├── env.py
│ ├── __pycache__
│ │ └── env.cpython-35.pyc
│ ├── README
│ ├── script.py.mako
│ └── versions
├── requirements.txt
├── setupdatabase.py
└── templates
└── home.html