ZeroByter ZeroByter - 3 months ago 21
Python Question

Setting a Cookie on a browser using Python

I have a project I'm working on. I would like to set a cookie when a user logs in so that they will be remembered. However I have tried every method on the internet, all the way from Google to Stack Overflow. I just cant seem to find a method that works.

I have tried:

class Main(webapp2.RequestHandler):
def get(self):
print "Set-Cookie: testing=test123cookie"
print "Content-Type: text/html\n"


And that didnt work. Then tried:

import Cookie

class Main(webapp2.RequestHandler):
def get(self):
cookie = Cookie.SimpleCookie()
cookie['lastvisit'] = "test"
print cookie
print 'Content-Type: text/html\n'


And surprise surprise, it doesn't work either. What do I do? How do I do it? I am sure I am just being stupid and not doing something right.

Thanks.

Answer

You need to use set_cookie() method:

class Main(webapp2.RequestHandler):
    def get(self):
        self.response.set_cookie('lastvisit', 'test', max_age=360, path='/')
Comments