首页 > 数据库技术 > 详细

flask之flask-sqlalchemy(一)

时间:2018-06-14 20:26:14      阅读:222      评论:0      收藏:0      [点我收藏+]

一 安装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()

 

 

五 创建数据库和数据表

技术分享图片

技术分享图片

 

flask之flask-sqlalchemy(一)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!