赞
踩
数据迁移就是将程序中定义的好的表结构映射到数据库中的过程,减少手动创建数据库表的麻烦。
Flask使用Flask-Migrate进行数据库对象迁移。
迁移的前提条件是在Python程序中定义好表结构,然后,进行如下操作:
- # 导入迁移对象
- from flask_migrate import Migrate as migrate
- # 实例化迁移对象
- grate = migrate(app, db)
- # 执行迁移步骤
- # migrate 的命令
- 1、flask db init ,#这步只执行一次
- 2、flask db migrate,#生成迁移脚本
- 3、flask db upgrate,#运行迁移脚本,同步到数据库中
案例代码如下:
- from flask import Flask, Response, request, render_template
- from flask_sqlalchemy import SQLAlchemy
- from sqlalchemy import text
- from urllib.parse import quote_plus as urlquote
- import random
- import uuid
- from datetime import datetime
- import sqlalchemy.types as types
- from flask_migrate import Migrate as migrate
-
- app = Flask(__name__)
-
- HOST = 数据库IP
- PORT = 数据库端口
- USERNAME = 用户名
- PASSWORD = 密码
- DATABASE = 数据库名
- strPwd = urlquote(PASSWORD)
- app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{strPwd}@{HOST}:{PORT}/{DATABASE}?charset=utf8"
-
- db = SQLAlchemy(app)
-
- grate = migrate(app, db)
- # migrate 的命令
- # 1、flask db init ,这步只执行一次
- # 2、flask db migrate,生成迁移脚本
- # 3、flask db upgrate,运行迁移脚本,同步到数据库中
-
- with app.app_context():
- with db.engine.connect() as conn:
- sql = text(" select * from xc_role ")
-
-
- # rs = conn.execute(sql)
- # print(rs.fetchone())
-
- class Role(db.Model):
- __tablename__ = "xc_role"
- id = db.Column(db.String(32), primary_key=True)
- role_name = db.Column(db.String(255), nullable=True)
- role_code = db.Column(db.String(255), nullable=True)
- description = db.Column(db.String(255), nullable=True)
- create_time = db.Column(db.DateTime, nullable=True)
- update_time = db.Column(db.DateTime, nullable=True)
- status = db.Column(db.String(1), nullable=True)
-
-
- @app.route("/add_role")
- def add_role():
- idStr = str(uuid.uuid4())
- idStr = idStr.replace("-", "")
- roleCodeStr = str(uuid.uuid4())
- role = Role(id=idStr, role_name=roleCodeStr, role_code=roleCodeStr, description="设置管理员角色",
- create_time=datetime.now(), update_time=datetime.now(), status="1")
- db.session.add(role)
- db.session.commit()
- return Response("添加角色信息成功", 200)
-
-
- @app.route("/query_role")
- def query_role():
- role = Role.query.get('308041566e7742829bd55867ca069473')
- print(f"{role.role_name}")
- return "查询角色成功"
-
-
- @app.route("/delete_role")
- def delete_role():
- role = Role.query.get('78c5411d945b40adb1b370c2a646b7b9')
- db.session.delete(role)
- db.session.commit()
- return "删除角色成功"
-
-
- @app.route("/update_role")
- def update_role():
- role = Role.query.get('308041566e7742829bd55867ca069473')
- role.role_name = "jijinliang"
- db.session.commit()
- return "更新角色成功"
-
-
- @app.route("/query_type")
- def query_type():
-
- return "查询类型成功"
-
-
- @app.route('/')
- def index():
- # put application's code here
- name = "名称"
- return render_template('index.html', name=name)
-
-
- @app.route('/show')
- def show():
- return Response("展示SHOW方法信息", 200)
-
-
- @app.route('/parse/<int:post_id>')
- def parse(post_id):
- """
- 解析信息
- """
- username = "jijinliang"
- return Response(f"解析信息方法{username},数字是:{post_id}", 200)
-
-
- @app.route("/page")
- def page():
- num = request.args.get("num", default=1, type=int)
- return Response(f"您当前访问的页面是{num}", 200)
-
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0', debug=True)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。