安装pip install flask_sqlalchemy -i https://pypi.douban.com/simple
flask目录结构
apps -- __init__py 里面加入Flask-SQLAlchemy第三方组件
- # -*- coding: utf-8 -*-
- from flask import Flask
- # 导入Flask-SQLAlchemy中的SQLAlchemy
- from flask_sqlalchemy import SQLAlchemy
- db = SQLAlchemy() # 初始化SQLAlchemy
- my_app = Flask(__name__)
- def create_app():
- # 配置数据库信息
- # SQLALCHEMY_DATABASE_URI 配置 SQLAlchemy 的链接字符串儿
- my_app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:redhat@192.168.32.71:3306/my_sql?charset=utf8"
- my_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 去掉异常警告信息
- my_app.config["SQLALCHEMY_POOL_SIZE"] = 5 # SQLALCHEMY_POOL_SIZE 配置 SQLAlchemy 的连接池大小
- my_app.config["SQLALCHEMY_POOL_TIMEOUT"] = 15 # SQLALCHEMY_POOL_TIMEOUT 配置 SQLAlchemy 的连接超时时间
- # 初始化SQLAlchemy , 本质就是将以上的配置读取出来
- db.init_app(my_app) # 初始化flask-app
- # 注册蓝图
- # 导包循环引用,哪里注册那里导入
- from .views.acc import acc
- from .views.user import user
- my_app.register_blueprint(acc) # 注册路由
- my_app.register_blueprint(user)
- return my_app
apps – models.py 里面加入Flask-SQLAlchemy
- # -*- coding: utf-8 -*-
- from apps import db, create_app
- # Base = db.Model
- # Base = declarative_base()
- # 每一次我们在创建数据表的时候都要做这样一件事
- # 然而Flask-SQLAlchemy已经为我们把 Base 封装好了 db
- class User(db.Model):
- # 默认__tablename__ 数据库名默认是类的小写
- __table_args__ = {"useexisting": True}
- id = db.Column(db.Integer, primary_key=True, autoincrement=True)
- name = db.Column(db.String(32))
- if __name__ == '__main__':
- my_app = create_app()
- db.drop_all(app=my_app)
- db.create_all(app=my_app)
apps – views – user.py 里面加入Flask-SQLAlchemy
- # -*- coding: utf-8 -*-
- from flask import Blueprint, jsonify
- from apps.models import User
- from apps import db
- user = Blueprint('user', __name__)
- @user.route('/user')
- def user_func():
- # 还记不记得我们的
- # from sqlalchemy.orm import sessionmaker
- # Session = sessionmaker(engine)
- # db_sesson = Session()
- # 现在不用了,因为 Flask-SQLAlchemy 也已经为我们做好会话打开的工作
- admin = User(name='admin')
- db.session.add(admin)
- db.session.commit()
- return 'user'
- @user.route('/user_list')
- def user_list():
- users = User.query.first()
- ret = {"name": users.name}
- return jsonify(ret)