1. 程式人生 > >Flask之session相關

Flask之session相關

decode python 所有 asdf signature logout print exc gin

Flask的session簡介

除請求對象之外,還有一個 session 對象。它允許你在不同請求間存儲特定用戶的信息。它是在 Cookies 的基礎上實現的,並且對 Cookies 進行密鑰簽名要使用會話,你需要設置一個密鑰。

  • 設置:session[‘username‘] = ‘xxx‘

  • 刪除:session.pop(‘username‘, None)
  • 獲取:session.get(‘username‘)

使用方法

from flask import Flask, session, redirect, url_for, escape, request
 
app = Flask(__name__)
 
@app.route(‘/‘)
def index():
    if ‘username‘ in session:
        return ‘Logged in as %s‘ % escape(session[‘username‘])
    return ‘You are not logged in‘
 
@app.route(‘/login‘, methods=[‘GET‘, ‘POST‘])
def login():
    if request.method == ‘POST‘:
        session[‘username‘] = request.form[‘username‘]
        return redirect(url_for(‘index‘))
    return ‘‘‘
        <form action="" method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    ‘‘‘
 
@app.route(‘/logout‘)
def logout():
    # remove the username from the session if it‘s there
    session.pop(‘username‘, None)
    return redirect(url_for(‘index‘))
 
# set the secret key.  keep this really secret:
app.secret_key = ‘A0Zr98j/3yX R~XHH!jmN]LWX/,?RT‘

基本使用

自定義session

pip3 install Flask-Session
        
        run.py
            from flask import Flask
            from flask import session
            from pro_flask.utils.session import MySessionInterface
            app = Flask(__name__)

            app.secret_key = ‘A0Zr98j/3yX R~XHH!jmN]LWX/,?RT‘
            app.session_interface = MySessionInterface()

            @app.route(‘/login.html‘, methods=[‘GET‘, "POST"])
            def login():
                print(session)
                session[‘user1‘] = ‘alex‘
                session[‘user2‘] = ‘alex‘
                del session[‘user2‘]

                return "內容"

            if __name__ == ‘__main__‘:
                app.run()

        session.py
            #!/usr/bin/env python
            # -*- coding:utf-8 -*-
            import uuid
            import json
            from flask.sessions import SessionInterface
            from flask.sessions import SessionMixin
            from itsdangerous import Signer, BadSignature, want_bytes


            class MySession(dict, SessionMixin):
                def __init__(self, initial=None, sid=None):
                    self.sid = sid
                    self.initial = initial
                    super(MySession, self).__init__(initial or ())


                def __setitem__(self, key, value):
                    super(MySession, self).__setitem__(key, value)

                def __getitem__(self, item):
                    return super(MySession, self).__getitem__(item)

                def __delitem__(self, key):
                    super(MySession, self).__delitem__(key)



            class MySessionInterface(SessionInterface):
                session_class = MySession
                container = {}

                def __init__(self):
                    import redis
                    self.redis = redis.Redis()

                def _generate_sid(self):
                    return str(uuid.uuid4())

                def _get_signer(self, app):
                    if not app.secret_key:
                        return None
                    return Signer(app.secret_key, salt=‘flask-session‘,
                                  key_derivation=‘hmac‘)

                def open_session(self, app, request):
                    """
                    程序剛啟動時執行,需要返回一個session對象
                    """
                    sid = request.cookies.get(app.session_cookie_name)
                    if not sid:
                        sid = self._generate_sid()
                        return self.session_class(sid=sid)

                    signer = self._get_signer(app)
                    try:
                        sid_as_bytes = signer.unsign(sid)
                        sid = sid_as_bytes.decode()
                    except BadSignature:
                        sid = self._generate_sid()
                        return self.session_class(sid=sid)

                    # session保存在redis中
                    # val = self.redis.get(sid)
                    # session保存在內存中
                    val = self.container.get(sid)

                    if val is not None:
                        try:
                            data = json.loads(val)
                            return self.session_class(data, sid=sid)
                        except:
                            return self.session_class(sid=sid)
                    return self.session_class(sid=sid)

                def save_session(self, app, session, response):
                    """
                    程序結束前執行,可以保存session中所有的值
                    如:
                        保存到resit
                        寫入到用戶cookie
                    """
                    domain = self.get_cookie_domain(app)
                    path = self.get_cookie_path(app)
                    httponly = self.get_cookie_httponly(app)
                    secure = self.get_cookie_secure(app)
                    expires = self.get_expiration_time(app, session)

                    val = json.dumps(dict(session))

                    # session保存在redis中
                    # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)
                    # session保存在內存中
                    self.container.setdefault(session.sid, val)

                    session_id = self._get_signer(app).sign(want_bytes(session.sid))

                    response.set_cookie(app.session_cookie_name, session_id,
                                        expires=expires, httponly=httponly,
                                        domain=domain, path=path, secure=secure)

自定義Session

第三方session

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
pip3 install redis
pip3 install flask-session

"""


from flask import Flask, session, redirect
from flask.ext.session import Session


app = Flask(__name__)
app.debug = True
app.secret_key = ‘asdfasdfasd‘


app.config[‘SESSION_TYPE‘] = ‘redis‘
from redis import Redis
app.config[‘SESSION_REDIS‘] = Redis(host=‘192.168.0.94‘,port=‘6379‘)
Session(app)


@app.route(‘/login‘)
def login():
    session[‘username‘] = ‘alex‘
    return redirect(‘/index‘)


@app.route(‘/index‘)
def index():
    name = session[‘username‘]
    return name


if __name__ == ‘__main__‘:
    app.run()

第三方session

 

Flask之session相關