pythonsessioncookies

Read Flask Session Cookie


I currently have the following:

from flask import Flask, session,request

@app.route('/venue/login', methods=['GET', 'POST'])
def venue_login():
    token = generate_token()
    session['venue_id'] = token
    return json.dumps(...)

When I look at the response in Chrome, I can see that Set-Cookie:session=... has been set.

I have 2 questions:

1) How do I read this cookie on the `server?

I have tried:

venue_id = request.cookies.get('venue_id')

but this doesn't seem to be picking it up.

2) With my code above, all my cookies will be set with the same name. After reading the cookie value, I would like to delete the corresponding entry in session. How should I go about doing this? Also if two requests come in one after the other, will the line:

session['venue_id'] = token

override the first entry with the second? Or does every request start a new session?

I am kind of confused with how this all should work. Any help would be greatly appreciated.


Solution

  • Well. Cookies and sessions are a bit different.

    If you want to use cookies and make venue_id = request.cookies.get('venue_id') work - You need to use set_cookie:
    set_cookie('venue_id', token)
    In cookies case - you can solve general problems that cookies can solve (have a long lasting cookie for example)

    If you want to use session (which is intended for session uniqueness and auth) you need to just use session and put the "username" or the unique ID of the venue in your case.

    Which to use - It really depends what you are trying to achieve

    Have a look at:
    https://flask.palletsprojects.com/en/3.0.x/quickstart/#cookies https://flask.palletsprojects.com/en/3.0.x/quickstart/#sessions