Flask-SQLAlchemy

models.pyhtml

from flask_sqlalchemy import SQLAlchemy

db=SQLAlchemy()

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 app01 import create_app
    app=create_app()
    db.create_all(app=app)
    # db.drop_all(app=app)

__init__.pymysql

from flask import Flask
from app01.models import db
from app01.views import user


def create_app():
    app = Flask(__name__)
    app.config["DEBUG"] = True
    app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123@127.0.0.1:3306/my_sqlalchemy?charset=utf8"


    app.config["SQLALCHEMY_POOL_SIZE"] = 50
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)

    app.register_blueprint(user.user_bp)


    return app

user.pysql

from flask import Blueprint
from app01.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.id)

manage.pyflask

from app01 import create_app

app = create_app()


if __name__ == '__main__':
    app.run()

参考 :http://www.javashuo.com/article/p-qjkrfexr-v.htmlsession

 

1.加入Flask-SQLAlchemy第三方组件

 
 

from flask import Flaskapp

 
 

# 导入Flask-SQLAlchemy中的SQLAlchemy
from flask_sqlalchemy import SQLAlchemy函数

 
 

# 实例化SQLAlchemy
db = SQLAlchemy()
# PS : 实例化SQLAlchemy的代码必需要在引入蓝图以前spa

 
 

from .views.users import usercode

 
 


def create_app():
app = Flask(__name__)orm

 
 

# 初始化App配置 这个app配置就厉害了,专门针对 SQLAlchemy 进行配置
# SQLALCHEMY_DATABASE_URI 配置 SQLAlchemy 的连接字符串儿
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:DragonFire@127.0.0.1:3306/dragon?charset=utf8"
# SQLALCHEMY_POOL_SIZE 配置 SQLAlchemy 的链接池大小
app.config["SQLALCHEMY_POOL_SIZE"] = 5
# SQLALCHEMY_POOL_TIMEOUT 配置 SQLAlchemy 的链接超时时间
app.config["SQLALCHEMY_POOL_TIMEOUT"] = 15
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

 
 

# 初始化SQLAlchemy , 本质就是将以上的配置读取出来
db.init_app(app)

 
 

app.register_blueprint(user)

 
 

return app

 
 

MyApp/__init__.py

 

创建models.py ORM模型文件

from MyApp import db

Base = db.Model # 这句话你是否还记的?
# from sqlalchemy.ext.declarative import declarative_base
# Base = declarative_base()
# 每一次咱们在建立数据表的时候都要作这样一件事
# 然而Flask-SQLAlchemy已经为咱们把 Base 封装好了

# 创建User数据表
class Users(Base): # Base实际上就是 db.Model
    __tablename__ = "users"
    __table_args__ = {"useexisting": True}
    # 在SQLAlchemy 中咱们是导入了Column和数据类型 Integer 在这里
    # 就和db.Model同样,已经封装好了
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(32))
    password = db.Column(db.String(32))


if __name__ == '__main__':
    from MyApp import create_app
    app = create_app()
    # 这里你要回顾一下Flask应该上下文管理了
    # 离线脚本:
    with app.app_context():
        db.drop_all()
        db.create_all()

MyApp/models.py

3.登陆视图函数的应用

from flask import Blueprint, request, render_template

user = Blueprint("user", __name__)

from MyApp.models import Users
from MyApp import db

@user.route("/login",methods=["POST","GET"])
def user_login():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")

        # 还记不记得咱们的
        # from sqlalchemy.orm import sessionmaker
        # Session = sessionmaker(engine)
        # db_sesson = Session()
        # 如今不用了,由于 Flask-SQLAlchemy 也已经为咱们作好会话打开的工做
        # 咱们在这里作个弊:
        db.session.add(Users(username=username,password=password))
        db.session.commit()

        # 而后再查询,捏哈哈哈哈哈
        user_info = Users.query.filter(Users.username == username and User.password == password).first()
        print(user_info.username)
        if user_info:
            return f"登陆成功{user_info.username}"

    return render_template("login.html")

MyApp/views/user.py
相关文章
相关标签/搜索