• [flask]flask_login模块,session及其他


    读flask源码的时候,有一点一直到现在都没有一个清晰的概念,比如四个全局变量g,current_app,session,request是怎么做到的

    按照查到的资料里面的说法,为了不至于每次都主动调用函数去获取请求值,所以在flask里面用了设计模式中的Proxy,在flask中用到了LocalProxy对四个全局变量进行代理,同时为了让其在多线程中可以访问,使用了类LocalStack,然后这四个变量都绑定到这个LocalStack的一个实例上面,就比如_request_ctx_stack,而这个类实现了把不同的请求绑定到不同的线程上面或者协程上面。然后就实现了不同请求的全局可用变量。

    但是看源码,这四个变量的生成方式是一样的,又怎么实现flask文档里面说的这些呢?

    比如:

    session: A session basically makes it possible to remember information from one request to another. 

    g:....

    还有flask_login 源码中的login_user和logout_user,除了用到了session,还把当前用户绑定到了_request_ctx_stack,为什么,不绑定不行吗?

     1 from flask import Flask, session, request
     2 app = Flask(__name__)
     3 app.secret_key = '~xc8xc6xe0xf3,x98Oxa8z4xfb=
    Nd'
     4 
     5 @app.route('/login')
     6 def login():
     7     uid =  request.args.get('uid')
     8     psw = request.args.get('psw')
     9     if uid and psw:
    10         session['uid'] = uid
    11         session['_login'] = True
    12         return '<h1>login succeed!</h1>'
    13     return '<h1>login failed</h1>'
    14 
    15 @app.route('/logout')
    16 def logout():
    17     if 'uid' in session:
    18         session.pop('uid')
    19     if '_login' in session:
    20         session.pop('_login')
    21         return '<h1>logout succeed</h1>'
    22     return '<h1>logout failed<h1>'
    23 
    24 
    25 @app.route('/test_login')
    26 def tst():
    27     if 'uid' in session:
    28         return '<h1>you are still in</h1>'
    29     else:
    30         return '<h1>you have logouted</h1>'
    31 if __name__ == '__main__':
    32     app.run(debug=True)

    同时分别用chrome和firefox去登录退出,证明是可以的,互不干扰,但是flask_login源码离那样写是基于什么考虑呢??

    写的很乱,先留下个问题吧

    参考资料:

    http://flask.pocoo.org/docs/0.10/api/#flask.request

    https://flask-login.readthedocs.io/en/latest/

    https://zhuanlan.zhihu.com/p/24629677

    http://www.zlovezl.cn/articles/charming-python-start-from-flask-request/

  • 相关阅读:
    并发通信、生产者消费者模型
    进程和线程的标识,守护模式
    IO多路复用
    网络编程(三):非阻塞套接字
    网络编程(二):套接字Socket
    网络编程(一):基础知识
    python标准库:base64模块
    @classmethod 和 @staticmethod
    Python特性及解释目录(不间断更新)
    Keras 整理及部分源码分析目录(不间断更新)
  • 原文地址:https://www.cnblogs.com/fcyworld/p/7161831.html
Copyright © 2020-2023  润新知