Home > Back-end >  Increment the cookie value in Flask
Increment the cookie value in Flask

Time:11-18

I want to count the number of visits to the page. Below is the code for the same. When I run the code, it doesn't set the 'visit_count' cookie and '/visit' returns 'None' value. What's the problem?

from flask.helpers import make_response
app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def show_page():
    return render_template('cookiecounter.html')

@app.route('/setcookie', methods=['GET','POST'])
def setcookie():
    resp = make_response('Welcome to our site!')
    resp.set_cookie('user_visit',str(1), max_age=5*60*60)
    return resp
   
@app.route('/visit', methods=['GET','POST'])  
def visit():
    vc=request.cookies.get('user_visit')
    if vc==1:
        return 'You are visiting for the first time'
    else:
        vscount=int(vc) 1
        resp1 = make_response('new visit')
        resp1.set_cookie('visit_count',str(vscount), max_age=5*60*60)
        inc_count=request.cookies.get('visit_count')
        return str(inc_count)

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

CodePudding user response:

There's a couple things going on that cause the unexpected result.

resp1.set_cookie('visit_count',str(vscount), max_age=5*60*60)

When you do this you're not actually setting the cookie's value yet, just preparing the response so that the cookie will be set once the client receives your response.

inc_count=request.cookies.get('visit_count')

Since the previous statement did not actually set any cookie, this is effectively retrieving the same value as when you first called it, which is the old value.

return str(inc_count)

Remember how you set up your response so that it would set a cookie on the client? Since you're not returning that response, the updated cookie is never set and you're left with the old one (which in your case is no cookie at all). Plus you're also returning the old value because you retrieved it in the line before.

Another thing is you're checking equality between your variable holding the string "1" and the number 1, that is probably not what you meant to do.

I'm not sure why you're using two different cookies user_visit and visit_count.

from flask.helpers import make_response
from flask import Flask, request
app = Flask(__name__)

@app.route('/visit', methods=['GET','POST'])  
def visit():
    vc=request.cookies.get('user_visit', "1")
    
    resp = make_response(f"This is visit number {int(vc)}")
    vscount=int(vc) 1
    resp.set_cookie('user_visit',str(vscount), max_age=5*60*60)
    return resp

This is probably close to what you wanted to achieve.

Happy pythoning

  • Related