Python web framework: Session

In addition to the request object, there is also a session object. It allows you to store specific user information between different requests. It is implemented on the basis of Cookies. To sign a key for Cookies, you need to set a key to use the session.

  • Settings: session ['username']='xxx'
  • Delete: session.pop('username', None)
from flask import Flask,url_for,session
//What problems do you not understand? Python Learning Exchange Group: 821460695 to meet your needs, information has been uploaded group files, you can download!
app = Flask(__name__)
app.secret_key = "sdsfdgdgdgd"
app.config['SESSION_COOKIE_NAME'] = 'session_lvning'  #Set the session name

def index(nid):
    #session essentially operates on a dictionary, and all sessions operate in the same way as dictionaries.
    #The principle of session: if you take the random string with the next visit, you will correspond to the session.
    # If session is saved in the database, linking the database once every time and updating it every time, the efficiency of the database will be greatly impaired.
    session["xxx"] = 123
    session["xxx2"] = 123
    session["xxx3"] = 123
    session["xxx4"] = 123
    del session["xxx2"]  #It's deleted here. There's no xxx2 when it's actually stored.
    return "ddsf"

if __name__ == '__main__':

About session Configuration

app.config['SESSION_COOKIE_NAME'] = 'session_lvning'

- How to set session timeout? 'PERMANENT_SESSION_LIFETIME': time delta (days = 31)
 Here are the session-related configuration files
            'SESSION_COOKIE_NAME':                  'session',
            'SESSION_COOKIE_DOMAIN':                None,
            'SESSION_COOKIE_PATH':                  None,
            'SESSION_COOKIE_HTTPONLY':              True,
            'SESSION_COOKIE_SECURE':                False,
            'SESSION_REFRESH_EACH_REQUEST': True, # Is it always new?
            'PERMANENT_SESSION_LIFETIME':           timedelta(days=31)

Basic use

from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
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>
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'

Custom Session

pip3 install Flask-Session
            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():
                session['user1'] = 'alex'
                session['user2'] = 'alex'
                del session['user2']

                return "content"

            if __name__ == '__main__':
            #!/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',

                def open_session(self, app, request):
                    //When the program is started, it needs to return a session object.
                    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)
                        sid_as_bytes = signer.unsign(sid)
                        sid = sid_as_bytes.decode()
                    except BadSignature:
                        sid = self._generate_sid()
                        return self.session_class(sid=sid)

                    # session is saved in redis
                    # val = self.redis.get(sid)
                    # session is saved in memory
                    val = self.container.get(sid)

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

                def save_session(self, app, session, response):
                    //Executing before the end of the program saves all the values in the session
                    //Such as:
                        //Save to resit
                        //Write to user 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 is saved in redis
                    # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)
                    # session is saved in memory
                    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)

Third party 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='',port='6379')

def login():
    session['username'] = 'alex'
    return redirect('/index')

def index():
    name = session['username']
    return name

if __name__ == '__main__':

Keywords: Session Redis Python Database

Added by akitchin on Mon, 07 Oct 2019 21:16:21 +0300