[英]Flask Migration integration in sqlite database
I am trying to integrate migration in the SQLite database in my Flask app.我正在尝试在 Flask 应用程序的 SQLite 数据库中集成迁移。 I have used我用过了
set FLASK_APP = Basic.py
in the terminal of Pycharm of the project directory then run在项目目录的Pycharm的终端然后运行
flask db init
But it is not working.但它不起作用。 Here are my codes:这是我的代码:
Basic.py
__author__ = 'User'
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate,MigrateCommand
basedir = os.path.abspath(os.path.dirname(__file__))
#__file__ -->Main.py
print(basedir)
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(app,db)
####################################################
class Puppy(db.Model):
#manual table name choice
__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)
__author__ = 'Mitu'
from Basic import db,Puppy
#CREATE ALL THE TABLES Model
db.create_all()
sam = Puppy('Sammy',3)
frank = Puppy('Frankie',4)
#none
#none
print(sam.id)
print(frank.id)
db.session.add_all([sam,frank])
db.session.commit()
print(sam.id)
print(frank.id)
__author__ = 'Mitu'
from Basic import db,Puppy
### Create ###
my_puppy = Puppy('Rufus',5)
db.session.add(my_puppy)
db.session.commit()
#### Read ####
all_puppies = Puppy.query.all() #list of all puppies object
print(all_puppies)
# select by id
puppy_one = Puppy.query.get(1)
print(puppy_one)
# filters
# produce some sl code!
puppy_frankie = Puppy.query.filter_by(name='Frankie')
print(puppy_frankie.all())
#["Frankie is 3 years old"]
#### update
first_puppy = Puppy.query.get(1)
first_puppy.age = 10
db.session.add(first_puppy)
db.session.commit()
#### delete
second_pup = Puppy.query.get(2)
db.session.delete(second_pup)
db.session.commit()
# now all puppies
all_puppies = Puppy.query.all()
print(all_puppies)
Last two files are for setup the database and for the CRUD operation of sqlite database.最后两个文件用于设置数据库和sqlite数据库的CRUD操作。
My main problem is migration is not integrating.我的主要问题是迁移没有集成。
I have installed the required packages in a virtual environment created using Python 3.5.我已经在使用 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
: 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
As flask-migrate
searches for app.py
when running flask db init
, I renamed Basic.py
to app.py
.当运行flask db init
时flask-migrate
搜索app.py
时,我将Basic.py
重Basic.py
为app.py
I ran attached setupdatabase.py
to create the SQLite database and crud.py
to create dummy records.我运行附加的setupdatabase.py
来创建 SQLite 数据库和crud.py
来创建虚拟记录。
I created a route to test if these SQLite data are being passed to Flask template.我创建了一个路由来测试这些 SQLite 数据是否被传递到 Flask 模板。
updated app.py
:更新的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
: home.html
:
<html>
<head>
<title>Home</title>
</head>
<body>
<h3>Puppies</h3>
<div>{{ data }}</div>
</body>
</html>
The data are passed to template:数据传递给模板:
Then I ran the init
, migrate
and upgrade
command as instructed in official documentation of flask-migrate .然后我按照 flask-migrate 官方文档中的说明运行了init
、 migrate
和upgrade
命令。
(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.
Directory structure after running the migrations (skipped venv folder):运行迁移后的目录结构(跳过 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.