Flask—06-理解掌握flask数据模型(02)

数据模型

模型关系

  • 一对多(使用最多)
    • 一:学生(Student)
      • 需要添加反向引用
    • 多:文章(Article)
      • 需要添加外键关联
  • 一对一
    • 一:学生(Student),主表
      • 需要添加反向引用,在一对多的情况下多指定属性userlist=False即可
    • 一:详情(Profile),次表
      • 需要添加外键关联
  • 多对多
    • 多:学生(Student)
      • 需要添加反向引用
      • 添加反向引用时需要通过secondary指定中间关联表
      • 设置反向引用的查询时机,可以通过db.backref完成
    • 多:课程(Course)
    • 中间关联表:学生选课表,不需要进行操作和维护
      • 字段:表名、外键关联

模型总结

  • 等价查询

    @app.route('/query/')
    def query():
        # students = Student.query.all()
        # 等价于
        students = db.session.query(Student).all()
        return ','.join(s.name for s in students)
    
  • 指定字段查询

    @app.route('/select/')
    def select():
        # ret = db.session.query(Student.id, Student.name).all()
        # 指定字段查询,等价于上式
        ret = Student.query.with_entities(Student.id, Student.name).all()
        # 返回指定字段组成的元组构成的列表
        print(ret)
        return '查询结束'
    
  • 分页查询:paginate,项目中讲解。

  • 查看SQL日志:就是查看执行过的SQL语句。

    # 记录SQL日志,需要满足以下三个条件中的任意一个即可
    # app.config['DEBUG'] = True
    # app.config['TESTING'] = True
    app.config['SQLALCHEMY_RECORD_QUERIES'] = True
    
    from flask_sqlalchemy import get_debug_queries
    
    queries = get_debug_queries()
    for q in queries:
        print(q)
    

数据缓存

  • 说明:

    数据库的速度是一个web应用的性能瓶颈,因此,为了提高访问效率,应该尽可能减少数据库的访问。可以将经常访问的数据缓存起来,每次访问时先从缓存中获取数据,若有直接返回;没有再从数据库中读取。

  • flask-cache:专门负责数据缓存的扩展。

  • 安装:pip install flask-cache

  • 使用:

    from flask_cache import Cache
    
    # 配置
    # 缓存类型
    app.config['CACHE_TYPE'] = 'redis'
    # 主机
    app.config['CACHE_REDIS_HOST'] = '127.0.0.1'
    # 端口
    app.config['CACHE_REDIS_PORT'] = 6379
    # 数据库
    app.config['CACHE_REDIS_DB'] = 1
    
    # 创建对象
    cache = Cache(app, with_jinja2_ext=False)
    
  • 缓存视图函数:

    @app.route('/')
    # timeout:指定缓存有效期,默认300s
    # key_prefix:缓存键前缀,默认:view/ + 路由地址
    @cache.cached(timeout=100, key_prefix='index')
    def index():
        print('读取数据库')
        return '有效数据'
    
  • 缓存普通函数:

    # 缓存普通函数,key_prefix必须指定
    @cache.cached(timeout=100, key_prefix='common')
    def common():
        print('查询数据库')
        return '返回的数据'
    
    @app.route('/hello/')
    def hello():
        return common()
    
  • 清除缓存

    @app.route('/clear/')
    def clear():
        # 指定删除
        # cache.delete('index')
        # 全部清空
        cache.clear()
        return '缓存已清除'
    
  • 自定义缓存

    @app.route('/zidingyi/')
    def zidingyi():
        # 先从缓存中获取
        data = cache.get('zidingyi_data')
        if data:
            return data
        # 没有缓存数据
        print('从数据库中获取数据')
        data = '123456'
        # 缓存数据
        cache.set('zidingyi_data', data, timeout=100)
        return data
    

posted @ 2018-10-05 16:19  Sunwj_Monkey  阅读(197)  评论(0编辑  收藏  举报