简体   繁体   中英

Flask - How to get session value that was set from Javascript?

Given the script below, I tried to get javascript session value in Flask via Python script as below:

JS Script

In javascript, I set session with DataMulti the value as below:

DataJson = [{Gender:'boy', FirstName:'Jonh', LastName:'Smith'},{Gender:'girl', FirstName:'Mary', LastName:'Smith'}]
    
sessionStorage.setItem('DataMulti', JSON.stringify(DataJson))

Python Script

Then in python script, I try to access that session key value via flask as this:

from flask import request, session

print('My session: ',session.get('DataMulti')) # null

However, the value I got is null . If I set another session inside python script directly, the session is working as fine:

session['firstName'] = "Jquery"

print(session.get('firstName')) # Jquery

Why it is like that? How can I get session value that is set from Javascript? Thanks

The session storage in js stores the data in Webbrowser so that you can retrieve it somewhere else in the js code. It has nothing to do with the data passed to the server in an HTTP session. Similarly, the session in the flask is for storing data to retrieve elsewhere in flask code. These are separated by a process boundary and are not linked to each other.

To send the data, you will have to do a post request and store the data in flask using the session.

# Handle post request in flask
session['data'] = request.json

To use this data elsewhere,

data = session.get('data', None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM