使用Python和Google App Engine的Cookie [英] Cookies using Python and Google App Engine

查看:89
本文介绍了使用Python和Google App Engine的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Google App Engine上开发应用程序,但遇到了问题。我想向每个用户会话添加一个cookie,以便能够区分当前用户。我希望他们都是匿名的,因此我不希望登录。为此,我为cookie实现了以下代码。

I'm developing an app on the Google App Engine and have run into a problem. I want to add a cookie to each user session so that I will be able to differentiate amongst the current users. I want them all to be anonymous, thus I do not want a login. Therefor I've implemented following code for cookies.

def clear_cookie(self,name,path="/",domain=None):
    """Deletes the cookie with the given name."""
    expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
    self.set_cookie(name,value="",path=path,expires=expires,
                    domain=domain)    

def clear_all_cookies(self):
    """Deletes all the cookies the user sent with this request."""
    for name in self.cookies.iterkeys():
        self.clear_cookie(name)            

def get_cookie(self,name,default=None):
    """Gets the value of the cookie with the given name,else default."""
    if name in self.request.cookies:
        return self.request.cookies[name]
    return default

def set_cookie(self,name,value,domain=None,expires=None,path="/",expires_days=None):
    """Sets the given cookie name/value with the given options."""

    name = _utf8(name)
    value = _utf8(value)
    if re.search(r"[\x00-\x20]",name + value): # Don't let us accidentally inject bad stuff
        raise ValueError("Invalid cookie %r:%r" % (name,value))
    new_cookie = Cookie.BaseCookie()
    new_cookie[name] = value
    if domain:
        new_cookie[name]["domain"] = domain
    if expires_days is not None and not expires:
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
    if expires:
        timestamp = calendar.timegm(expires.utctimetuple())
        new_cookie[name]["expires"] = email.utils.formatdate(timestamp,localtime=False,usegmt=True)
    if path:
        new_cookie[name]["path"] = path
    for morsel in new_cookie.values():
        self.response.headers.add_header('Set-Cookie',morsel.OutputString(None))

要测试以上内容代码我使用了以下代码:

To test the above code I've used the following code:

class HomeHandler(webapp.RequestHandler):
    def get(self):
        self.set_cookie(name="MyCookie",value="NewValue",expires_days=10)
        value1 = str(self.get_cookie('MyCookie'))    
        print value1

运行此文件时,HTML文件中的标题如下:

When I run this the header in the HTML file looks as follows:



状态:200 OK
内容类型:text / html; charset = utf-8
缓存控制:无缓存
Set-Cookie:MyCookie = NewValue; expires =星期四,2012年12月6日17:55:41 GMT; Path = /
Content-Length:1199

None Status: 200 OK Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Set-Cookie: MyCookie=NewValue; expires=Thu, 06 Dec 2012 17:55:41 GMT; Path=/ Content-Length: 1199

上面的无是指代码中的 value1 。

"None" in the above refers to the "value1" from the code.

您能否告诉我为什么cookie值即使被添加到标题中也为 None?

Can you please tell me why the cookie value is "None", even when it is added to the header?

非常感谢您的帮助。

推荐答案

调用 set_cookie(),它将在正在准备的响应上设置cookie(即,在函数返回后,将在发送响应时设置cookie)。对 get_cookie()的后续调用是从当前请求的标题中读取的。由于当前请求没有要测试的cookie集,因此不会读取该cookie。但是,如果您要重新访问此页面,您会得到不同的结果,因为cookie现在将成为请求的一部分。

When you call set_cookie(), it is setting the cookie on the response it is preparing (that is, it will set the cookie when the response is sent, after your function returns). The subsequent call to get_cookie() is reading from the headers of the current request. Since the current request did not have a cookie set that you are testing for, it will not be read in. However, if you were to revisit this page, you should get a different result as the cookie will now be part of the request.

这篇关于使用Python和Google App Engine的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆