简体   繁体   中英

Retrieve localStorage data using Flask

I am working on a project that requires user login/logout. I have managed to pass data and store them in the localStorage. However, I cannot find the easiest way to integrate Flask with the localStorage file without using jQuery. I would love to have some suggestions from people who have already tried this out before. Here are my Python script and JavaScript code

Here is the Python Flask script:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/login")
def login():
    # DO SOMETHING TO AUTHENTICATE USER AND GENERATE TOKEN
    return render_template("base.html", token="token")

@app.route("/logout")
def logout():
    # RETRIEVE TOKEN FROM LOCAL STORAGE
    return "Success"

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

Here is the HTML + JavaScript simplify code:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1> Hello </h1>
    <script type="text/javascript">
      // STORE TOKEN INTO LOCALSTORAGE
      localStorage.setItem("token", "{{token}}");
    </script>
  </body>
</html>

localStorage lives on the browser side of things. The server can't access it directly.

You'll need to send the token from the client to the server when the user presses the logout button in your app.

document.getElementById('logout').onclick = function logout() {
    let token = localStorage.getItem('token')

    // use your favourite AJAX lib to send the token to the server as e.g. JSON

    // redirect user to e.g. landing page of app if logout successul, show error otherwise
}

Your view will receive the token and do something useful with it.

@app.route("/logout")
def logout():
    token = request.get_json()['token']

    # log the user out

    return jsonify({'status':'success'})

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