zoukankan      html  css  js  c++  java
  • 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() 清空表

  • 相关阅读:
    将数字转化为字符串
    给定一列数字将其平移n位
    判断回文数的问题
    c语言链表逆序的问题
    python中类属性和实例属性的区别
    python中__repr__()方法
    python中模块和包
    flask如何写一个model
    遍历文件夹下excel文件并且写入一个新excel
    python统计任务耗时
  • 原文地址:https://www.cnblogs.com/lfxiao/p/9184276.html
Copyright © 2011-2022 走看看