Sunday, November 8, 2009

Reading and Writing Cookies

Since runaround application uses Cookies to store the username, in this post we will see how to read and write using webapp framework.

Reading cookies is quite simple:

if request.cookies.has_key(USER_COOKIE_NAME):
            username = request.cookies[USER_COOKIE_NAME]
        

Writing cookies:

I have created a small function that should help:

def writeCookie(response,username):
    cookie = Cookie.SimpleCookie()
    cookie[USER_COOKIE_NAME] = username
    cookie[USER_COOKIE_NAME]["Path"] = "/"
    
    h = re.compile('^Set-Cookie:').sub('',cookie.output(),count=1)
         
    response.headers.add_header('Set-Cookie',str(h))

0 comments:

Post a Comment