Database migration
Migrate the database by creating a virtual flask environment.
First, create a virtual environment
virtualenvwrapper
There is a function in the library mkvirtualenv
to create a virtual environment (make Vsan envirement). Using commands
mkvirtualenv flask-tutorial --python=python3.6
Create a "flask-tutorial
virtual Environment,
can take advantage of workon flask-tutorial
command activates this virtual environment. Use deactivate
exits this virtual environment. Under default conditions, the virtual environment does not contain any libraries. Therefore, a reinstallation is required.
pip install flask flask-login flask-sqlalchemy mysql-connector-python
Then pip freeze
, by looking at the library, you will see:
-f/usr/share/pip-wheelsclick==6.7flask==0.12.2flask-login==0.4.0flask-sqlalchemy== 2.3.2itsdangerous==0.24jinja2==2.9.6markupsafe==1.0mysql-connector-python==2.0.4sqlalchemy==1.1.14werkzeug== 0.12.2
Use pip freeze > requirements.txt
to generate requirements.txt this file. Note Delete the first line of -f /usr/share/pip-wheels
git again.
Second, install Flask Database Migration Extension flask-migrate
Use to pip install Flask-Migrate
install this extension.
fromimport Migrate migrate = Migrate(app, db)
Add the above code in flask_app.py to enable migrate.
Create a directory where the migration will take place,
Command:
export flask_app=flask_app.pyflask DB init
Then create a new database and replace the old database in flask_app.py. Save but do not run. Command line Input flask db migrate
, then change the changes back. flask db migrate
generates a. py file that is used to modify the comments database.
Then executes the command line flask db stamp head
adds a version number to the comments database.
Go to Database console to execute:
show Tables;select * from alembic_version;
Results
The original comments database was found to have changed at this time: increased alembic_version
, which is the underlying library flask-migrate used to complete the work. Where the Version_num column has only one line of hexadecimal digits, which is executed
flask db stamp head
The resulting numbers are the same and can be understood as the "version number" that Flask_migrate added for the comments database.
Iv. add a new column for the comments database.
The work ahead is done, and the following can be added in the flask_app.py comments classposted = db.Column(db.DateTime, default=datetime.now)
。 Then enter the following command line in turn:
1.flask db migrate
A python file is generated that is required to update the database.
Notice that the new file addsupgrade()
The function is used to increase the posted column.
2.flask db upgrade
Execute the above file to add columns to the database.
Check MySQL at this time and find that posted has been added.
?
Flask Study Notes (3)-Database migration