flask数据迁移

原创
2018/06/21 17:22
阅读数 78

flask数据迁移

^C(py3env) root@alex-virtual-machine:/www/flask-learn# clear
(py3env) root@alex-virtual-machine:/www/flask-learn# flask db init
  Creating directory /www/flask-learn/migrations ... done
  Creating directory /www/flask-learn/migrations/versions ... done
  Generating /www/flask-learn/migrations/env.py ... done
  Generating /www/flask-learn/migrations/script.py.mako ... done
  Generating /www/flask-learn/migrations/README ... done
  Generating /www/flask-learn/migrations/alembic.ini ... done
  Please edit configuration/connection/logging settings in '/www/flask-learn/migrations/alembic.ini' before proceeding.
(py3env) root@alex-virtual-machine:/www/flask-learn# flask db 



(py3env) root@alex-virtual-machine:/www/flask-learn# flask db migrate -m "users table"
Traceback (most recent call last):  File "/www/env/py3env/bin/flask", line 11, in <module>    sys.exit(main())  File "/www/env/py3env/lib/python3.5/site-packages/flask/cli.py", line 894, in main
    cli.main(args=args, prog_name=name)  File "/www/env/py3env/lib/python3.5/site-packages/flask/cli.py", line 557, in main
    return super(FlaskGroup, self).main(*args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)  File "/www/env/py3env/lib/python3.5/site-packages/click/core.py", line 1066, in invoke    return _process_result(sub_ctx.command.invoke(sub_ctx))  File "/www/env/py3env/lib/python3.5/site-packages/click/core.py", line 1066, in invoke    return _process_result(sub_ctx.command.invoke(sub_ctx))  File "/www/env/py3env/lib/python3.5/site-packages/click/core.py", line 895, in invoke    return ctx.invoke(self.callback, **ctx.params)  File "/www/env/py3env/lib/python3.5/site-packages/click/core.py", line 535, in invoke    return callback(*args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/click/decorators.py", line 17, in new_func    return f(get_current_context(), *args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/flask/cli.py", line 412, in decorator    return __ctx.invoke(f, *args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/click/core.py", line 535, in invoke    return callback(*args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/flask_migrate/cli.py", line 90, in migrate
    rev_id, x_arg)  File "/www/env/py3env/lib/python3.5/site-packages/flask_migrate/__init__.py", line 95, in wrapped
    f(*args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/flask_migrate/__init__.py", line 215, in migrate
    version_path=version_path, rev_id=rev_id)  File "/www/env/py3env/lib/python3.5/site-packages/alembic/command.py", line 176, in revision
    script_directory.run_env()  File "/www/env/py3env/lib/python3.5/site-packages/alembic/script/base.py", line 427, in run_env
    util.load_python_file(self.dir, 'env.py')  File "/www/env/py3env/lib/python3.5/site-packages/alembic/util/pyfiles.py", line 81, in load_python_file    module = load_module_py(module_id, path)  File "/www/env/py3env/lib/python3.5/site-packages/alembic/util/compat.py", line 83, in load_module_py
    spec.loader.exec_module(module)  File "<frozen importlib._bootstrap_external>", line 665, in exec_module  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed  File "migrations/env.py", line 87, in <module>
    run_migrations_online()  File "migrations/env.py", line 70, in run_migrations_online
    poolclass=pool.NullPool)  File "/www/env/py3env/lib/python3.5/site-packages/sqlalchemy/engine/__init__.py", line 465, in engine_from_config    return create_engine(url, **options)  File "/www/env/py3env/lib/python3.5/site-packages/sqlalchemy/engine/__init__.py", line 424, in create_engine    return strategy.create(*args, **kwargs)  File "/www/env/py3env/lib/python3.5/site-packages/sqlalchemy/engine/strategies.py", line 81, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)  File "/www/env/py3env/lib/python3.5/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 102, in dbapi    return __import__('MySQLdb')
ImportError: No module named 'MySQLdb'报错没有安装  MySQLdb
Successfully installed PyMySQL-0.8.1安装完扩展,重新执行迁移命令,生成数据成功
(py3env) root@alex-virtual-machine:/www/flask-learn# flask db migrate -m "users table"INFO  [alembic.runtime.migration] Context impl MySQLImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added table 'users'
  Generating /www/flask-learn/migrations/versions/c225543b8ab9_users_table.py ... done
(py3env) root@alex-virtual-machine:/www/flask-learn# 
配置文件
config.py
#!/usr/bin/env python

#encoding:utf-8

import os
class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or  'mysql+pymysql://root:123456@127.0.0.1/book'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

 

manage.py
#!/usr/bin/env python

#encoding:utf8

"""
pip install flask-migrate  i http://pypi.douban.com/simple/
pip install flask_bootstrap  i http://pypi.douban.com/simple/
pip install flask_wtf  i http://pypi.douban.com/simple/
pip install flask_sqlalchemy i http://pypi.douban.com/simple/
 pip install PyMySQL

"""

from flask import Flask,render_template,session,redirect,url_for,flash,get_flashed_messages
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import Length,DataRequired
from config import  Config
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_migrate import Migrate


app = Flask(__name__)

app.config.from_object(Config)
# 数据库配置 start

#MySQL	mysql+pymysql://username:password@hostname/database

# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1/book'

# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

# enddb = SQLAlchemy(app)

migrate = Migrate(app, db)


bootstrap = Bootstrap(app)

class User(db.Model):
    """定义数据模型"""
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(80),unique=True)
    email = db.Column(db.String(120),unique=True)   
    def __init__(self,username,email):
        self.username = username
        self.email = email    
    def __repr__(self):
        return '<User %r>' % self.username
    
class Login(FlaskForm):
    username = StringField(u'用户名',validators=[DataRequired(message='用户名不能为空'),Length(min=6,max=12,message='用户名长度为 6~12 位')])
    userpass = PasswordField(u'密码',validators=[DataRequired(message='密码不能为空'),Length(min=6,max=12,message='密码长度为 6-12 位')])
    submit = SubmitField('登录')


@app.route("/index",methods=['GET','POST'])
def index():
    form = Login()   
     if form.validate_on_submit():
        print(form.username.data)
        flash("注册成功")       
          return redirect(url_for('home'))   
          return render_template('hello.html',form=form)
          
          
@app.route("/home")
def home():
    return render_template("home.html")

if __name__ == "__main__":
    app.run(host='0.0.0.0',debug=True)
执行迁移前需要配置环境变量,在 python 虚拟环境下设置环境变量

(py3env) root@alex-virtual-machine:/www/flask-learn# flask Usage: flask [OPTIONS] COMMAND [ARGS]...

  A general utility script for Flask applications.

  Provides commands from Flask, extensions, and the application. Loads the
  application defined in the FLASK_APP environment variable, or from a
  wsgi.py file. Setting the FLASK_ENV environment variable to 'development'
  will enable debug mode.

    $ export FLASK_APP=hello.py
    $ export FLASK_ENV=development
    $ flask runOptions:
  --version  Show the flask version
  --help     

export FLASK_APP=manage.py

 

flask db migrate命令不会对数据库进行任何更改,只会生成迁移脚本。 要将更改应用到数据库,必须使用flask db upgrade命令。

所以upgrade命令检测到数据库不存在时,会创建它(在这个命令完成之后,你会注意到一个名为app.db的文件,即 SQLite 数据库)。 在使用类似 MySQL 和 PostgreSQL 的数据库服务时,必须在运行upgrade之前在数据库服务器上创建数据库。

 

(py3env) root@alex-virtual-machine:/www/flask-learn# flask db upgrade
INFO [alembic.runtime.migration] Context impl MySQLImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.runtime.migration] Running upgrade -> c225543b8ab9, users table

 

查看数据库生成数据库成功

mysql> show tables;
+-----------------+
| Tables_in_book  |
+-----------------+
| alembic_version |
| users           |
+-----------------+2 rows in set (0.00 sec)

mysql> desc users;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(80)  | YES  | UNI | NULL    |                |
| email    | varchar(120) | YES  | UNI | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

 

 

添加数据

@app.route('/adduser')def add_user():
    user1 = User('小麦','xiaomai@163.com')
    user2 = User('admin2','admin@163.com')

    db.session.add(user1)
    db.session.add(user2)
    db.session.commit()    return '添加成功'
mysql> select * from users;
+----+----------+-----------------+
| id | username | email           |
+----+----------+-----------------+
|  1 | 小麦     | xiaomai@163.com |
|  2 | admin2   | admin@163.com   |
+----+----------+-----------------+2 rows in set (0.00 sec)
命令行模式下查询和添加数据>>> from manage import User,db>>> user1 = User('jack','jack@163.com')>>> db.session.add(user1)>>> db.session.commit()>>> users =User.query.all()>>> users
[<User '小麦'>, <User 'admin2'>]>>> user1 = User('jack','jack@163.com')
>>> user = User.query.filter_by(username='jack').first()>>> user
<User 'jack'>
更新数据>>> user = User.query.filter_by(username='jack').first()>>> user.email = 'ceshi@qq.com'>>> db.session.add(user)>>> db.session.commit()>>> user = User.query.filter_by(username='jack').first()>>> user.email'ceshi@qq.com'>>> 
删除数据

user = User.query.filter_by(username='jack').first()>>> db.session.delete(user)>>> db.session.commit()

 

更多内容请关注我的订阅号:

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部