【Flask】Flask session

Flask Sessions (session)

Since HTTP is stateless, it cannot record a series of actions of the client. There must be a mechanism to enable the server to recognize the client. This introduces the concept of "session"! The
server sends the client a session ID, and when the client accesses the server again With this ID, the server uses this unique ID to identify the user.

Unlike cookies, Session data is stored on the server. The session is the time interval for the client to log in to the server and log out of the server. The data that needs to be saved in this session will be stored in a temporary directory on the server.

Assign a session ID to each client's session . The session data is stored on top of the cookie, and the server signs it in an encrypted manner. For this encryption, the Flask application needs a defined SECRET_KEY .

The Session object is also a dictionary object, containing key-value pairs of session variables and associated values.

For example, to set a'username' session variable, use the following statement:

Session['username'] = 'admin'

To release the session variable, use the pop() method.

session.pop('username', None)

The following code is a simple demonstration of the session work in Flask. The URL  '/' just prompts the user to log in because the session variable'username ' is not set .

@app.route('/')
def index():
   if 'username' in session:
      username = session['username']
         return 'Logged in as ' &plus; username &plus; '<br>' &plus; \
         "<b><a href = '/logout'>click here to log out</a></b>"
   return "You are not logged in <br><a href = '/login'></b>" &plus; \
      "click here to log in</b></a>"

When the user browses to the "/login" login() view function, because it is called by the GET method, a login form will open.

The form is sent back to '/login' and now the session variables are set. The application redirects to '/' . At this time the session variable'username ' is found.

@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>
      <p<<input type = submit value = Login/></p>
   </form>
	
   '''

The application also contains a logout() view function, which will pop up the'username' session variable. Therefore, the '/'  URL displays the start page again.

@app.route('/logout')
def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('index'))

Run the application and visit the home page. (Make sure to set the secret_key of the application )

from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'any random string’

The complete code is as follows

from flask import Flask

from flask import render_template

from flask import request

from flask import make_response

from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)

app.secret_key = 'fkdjsafjdkfdlkjfadskjfadskljdsfklj'

@app.route('/')
def index():
    if 'username' in session:
        username = session['username']
        return '登录用户名是:' + username + '<br>' + "<b><a href = '/logout'>点击这里注销</a></b>"
    return "您暂未登录, <br><a href = '/login'></b>" + "点击这里登录</b></a>"

@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>
      <p><input type ="submit" value ="登录"/></p>
   </form>
   '''

@app.route('/logout')
def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug = True)

The output will be shown below. Click the "Click here to log in" link.

The link will be directed to another screen. Type "admin".

The screen will display the message "The  login user name is: admin  "

Guess you like

Origin blog.csdn.net/u013066730/article/details/108361349