Flask_SQLAlchemy 缺乏、安全感 2023-08-17 16:53 113阅读 0赞 ## 准备 ## 安装Flask-SQLAlchemy这个模块 pip3 install flask_sqlalchemy ## 开始创建Flask项目 ## 创建项目目录(类似于Django项目) ![1614698-20190731210959625-313310424.png][] 接下来基于这个Flask项目,加入Flask-SQLAlchemy ![ContractedBlock.gif][] ![ExpandedBlockStart.gif][] from flask_sql import create_app # 注意不要放在main下面 app = create_app() if __name__ == '__main__': app.run() manage.py ## 1.加入Flask-SQLAlchemy第三方组件(在\_\_init\_\_.py里) ## from flask import Flask from flask_sql.views import user from flask_sql.models import db def create_app(): app = Flask(__name__) app.config["DEBUG"] = True app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root@127.0.0.1:3306/sqlalchemy?charset=utf8" app.config["SQLALCHEMY_POOL_SIZE"] = 50 # 数据量访问大时加上,数据库连接池,最大50个长连接 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) app.register_blueprint(user.user_bp) return app ## 2.建立models.py ORM模型文件(在models.py文件下) ## from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # 创建Users数据表 class Users(db.Model): __tablename__ = "users_flask" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), nullable=False) if __name__ == '__main__': from flask_sql import create_app app = create_app() db.create_all(app=app) # db.drop_all(app=app) ## 3.登录视图函数的应用(views/user.py文件下) ## from flask import Blueprint from flask_sql.models import Users, db user_bp = Blueprint("user_bp", __name__) @user_bp.route("/add_user/<username>", methods=["POST", "GET"]) def add_user(username): u = Users(name=username) db.session.add(u) db.session.commit() return "200 ok I am user_bp" @user_bp.route("/get_user/<username>", methods=["POST", "GET"]) def get_user(username): u = Users.query.filter(Users.name == username).first() return str(u.name) ## 运行manage.py开启项目test ## ![1614698-20190731211544670-1717787611.jpg][] ![1614698-20190731211557681-2119464220.jpg][] **运行成功 ok !!!** 转载于:https://www.cnblogs.com/biao-wu/articles/11278833.html [1614698-20190731210959625-313310424.png]: /images/20230809/9f8ccdbf51b24385aeea761a44e6f1c4.png [ContractedBlock.gif]: https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif [ExpandedBlockStart.gif]: /images/20230809/78114c25ee3b4ad7a368b5ce731fb8a2.png [1614698-20190731211544670-1717787611.jpg]: /images/20230809/a9b54a53deac40adaebc9e3edb996fe3.png [1614698-20190731211557681-2119464220.jpg]: /images/20230809/6a373f3da3964adfb6e5304a24c0d960.png
还没有评论,来说两句吧...