zoukankan      html  css  js  c++  java
  • Flask——g对象,flask_session,数据库连接池,wtforms,信号,

    g 对象

    g 是一个全局变量,存取自定义的变量
    session对象是可以跨request的,只要session还未失效,不同的request的请求会获取到同一个session,但是g对象不是,g对象不需要管过期时间,请求一次g对象就改变了一次,或者重新赋值了一次
    

    flask-session

    # 替换flask内置的session,支持存到redis,存到数据库
    
    # flask-session如何使用
    	方式一:
    conn=redis.Redis(host='127.0.0.1',port=6379)
    app.session_interface=RedisSessionInterface(conn,'lqz',permanent=False)
        方式二:
    from redis import Redis
    from flask.ext.session import Session
    app.config['SESSION_TYPE'] = 'redis'
    
    app.config['SESSION_KEY_PREFIX'] = 'lqz'
    
    app.config['SESSION_REDIS'] = Redis(host='127.0.0.1',port='6379')
    # # 本质跟上面一样
    # # 类似的用法在flask中很常见 函数(app)
    Session(app)
    
    
    # 问题1
    	-关闭浏览器cookie失效
        app.session_interface=RedisSessionInterface(conn,key_prefix='lqz',permanent=False)
    # 问题2 
    	-cookie默认超时时间是多少?如何设置超时时间
        'PERMANENT_SESSION_LIFETIME':           timedelta(days=31),#这个配置文件控制
    

    数据库连接池

    # pip install DBUtils
    import pymysql
    from DBUtils.PooledDB import PooledDB
    import time
    from threading import Thread
    POOL = PooledDB(
        creator=pymysql,  # 使用链接数据库的模块
        maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
        mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
        maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
        maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
        blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
        maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
        setsession=[],  # 开始会话前执行的命令列表。
        ping=0,
        # ping MySQL服务端,检查是否服务可用。
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123',
        database='flask',
        charset='utf8'
    )
    
    def func():
    # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
    #     # 否则
    #     # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
    #     # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
    #     # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
    #     # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
        conn = POOL.connection()
    
        # print(th, '链接被拿走了', conn1._con)
        # print(th, '池子里目前有', pool._idle_cache, '
    ')
    
        cursor = conn.cursor()
        cursor.execute('select * from boy')
        result = cursor.fetchall()
        time.sleep(2)
        conn.close()
    
    if __name__ == '__main__':
        for i in range(10):
            t=Thread(target=func)
            t.start()
    
    
    
    import pymysql
    from settings import Config
    class SQLHelper(object):
    
        @staticmethod
        def open(cursor):
            POOL = Config.PYMYSQL_POOL
            conn = POOL.connection()
            cursor = conn.cursor(cursor=cursor)
            return conn,cursor
    
        @staticmethod
        def close(conn,cursor):
            conn.commit()
            cursor.close()
            conn.close()
    
        @classmethod
        def fetch_one(cls,sql,args,cursor =pymysql.cursors.DictCursor):
            conn,cursor = cls.open(cursor)
            cursor.execute(sql, args)
            obj = cursor.fetchone()
            cls.close(conn,cursor)
            return obj
    
        @classmethod
        def fetch_all(cls,sql, args,cursor =pymysql.cursors.DictCursor):
            conn, cursor = cls.open(cursor)
            cursor.execute(sql, args)
            obj = cursor.fetchall()
            cls.close(conn, cursor)
            return obj
        @classmethod
        def execute(cls,sql, args,cursor =pymysql.cursors.DictCursor):
            conn, cursor = cls.open(cursor)
            cursor.execute(sql, args)
            cls.close(conn, cursor)
    

    wtforms(forms组件)

    1 校验数据
    2 渲染标签
    

    信号

    2 signal翻译过来的,flask的signal
    3 信号是同步操作
    4 如何使用(内置的)
    	# 内置信号的使用
        # 第一步写一个函数(触发某些动作)
        # 往信号中注册函数
        def func(*args,**kwargs):
            print(args[0])  # 当前app对象
            print('触发信号',args,kwargs)
        # 第二步:函数跟内置信号绑定
        signals.request_started.connect(func)
        
    5 自定义信号的使用
        #第一步:定义一个信号
        xxxxx = _signals.signal('xxxxx')
        # 第二步:定义一个函数
        def func3(*args,**kwargs):
            import time
            time.sleep(1)
            print('触发信号',args,kwargs)
        #第三步:信号跟函数绑定
        xxxxx.connect(func3)
    
        #第四步:触发信号
        xxxxx.send(1,k='2')
    
  • 相关阅读:
    xen xl命令记录
    fiefox 自动下载文件配置
    ActionChains用法
    WebDriverWait
    python3 安装selenium
    mysql 不能执行delete检查safe-updates模式
    shell 自动部署替换版本和备份
    matlab 非线性拟合
    【递归】1208:2的幂次方表示
    二进制和位运算符
  • 原文地址:https://www.cnblogs.com/pythonwl/p/13609399.html
Copyright © 2011-2022 走看看