flask之flask-sqlalchemy(一)

一 安装flask-sqlalchemy

pip install flask-sqlalchemy

二 导入相关模块和对象

from flask_sqlalchemy import SQLAlchemy

三 配置

# 此处是配置SQLALCHEMY_DATABASE_URI, 前面的mysql+pymysql指的是数据库的类型以及驱动类型
# 后面的username,pwd,addr,port,dbname分别代表用户名、密码、地址、端口以及库名

app.config[
'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/firewall' # 这里登陆的是root用户,要填上自己的密码,MySQL的默认端口是3306 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # ???True会报错

# 创建1个SQLAlichemy实例
db = SQLAlchemy(app)

四 定义数据表映射类

class StaticRoute(db.Model):
    __tablename__ = 'static_route_config'

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    d_ip_mask = db.Column(db.String(100), unique=False, nullable=False)
    next_gateway = db.Column(db.String(100), unique=False, nullable=False)

    __mapper_args__ = {
        "order_by": id.desc()
    }

    def __init__(self, d_ip_mask, next_gateway):
        self.d_ip_mask = d_ip_mask
        self.next_gateway = next_gateway

    @staticmethod
    def add_db(d_ip_mask, next_gateway):
        db.session.add(StaticRoute(d_ip_mask, next_gateway))
        db.session.commit()

    # python中使用默认值实现函数的重载
    @staticmethod
    def get_db(id=-1):
        if id >= 0:
            return StaticRoute.query.get(id)
        else:
            return StaticRoute.query.order_by('id')

    @staticmethod
    def del_db(id):
        db.session.delete(StaticRoute.query.get(id))
        db.session.commit()

    @staticmethod
    def update_db(id, d_ip_mask, next_gateway):
        sr = StaticRoute.query.get(id)
        sr.d_ip_mask = d_ip_mask
        sr.next_gateway = next_gateway
        db.session.add(sr)
        db.session.commit()

五 创建数据库和数据表

在创建表之前,最好先 清空一下表,再创建,不然会报一些奇怪的错误 ,使用db.create_all() 清空表

原文地址:https://www.cnblogs.com/lfxiao/p/9184276.html