Definition of Session
The Session object stores the properties and configuration information required for a specific user session. This way, when a user jumps between the application's Web pages, the variables stored in the session object are not lost, but persist throughout the user's session. When a user requests a Web page from an application, if the user does not yet have a session, the Web server automatically creates a Session object. When the session expires or is discarded, the server terminates the session. One of the most common uses of Session objects is to store the user's preferences.
The operation of the session is as follows
1 fromFlaskImportflask,session2 ImportOS3 fromDatetimeImportTimedelta4App = Flask (__name__)5app.config['Secret_key']=os.urandom (24)#set to 24-bit characters, each running the server is different, so the server starts one time the last session is cleared. 6app.config['Permanent_session_lifetime']=timedelta (days=7) #设置session的保存时间. 7 #add data to session8 #The operation of the dictionary is the same time9 #Secret_key:----------Salt, in order to confuse encryption. Ten One A@app. Route ('/') - defHello_world (): -Session.permanent=true#默认Duration of Session lasts 31 days thesession['username'] ='XXX' - - return 'Hello world!' - + #Get Session -@app. Route ('/get/') + defget (): A returnSession.get ('username') at - #Delete Session -@app. Route ('/delete/') - defDelete (): - Print(Session.get ('username')) -Session.pop ('username') in Print(Session.get ('username')) - return 'Delete' to #Clear Session +@app. Route ('/clear/') - defClear (): the Print(Session.get ('username')) * session.clear () $ Print(Session.get ('username'))Panax Notoginseng return 'Clear' - the if __name__=='__main__': +App.run (Debug=true)
Secret_key
Secret_key is set to Os.urandom (24) This is not appropriate in the project, because the value will change when the server is not started, so all saved sessions are invalidated. It's just a learning phase, so it can be generated randomly.
Python Framework Flask Learning Notes Session