2012-11-26 2 views
5

Google App Engineでアプリケーションを開発していて、問題が発生しました。私は現在のユーザーの間で区別できるように、各ユーザーセッションにCookieを追加したいと思います。私はそれらをすべて匿名にしたいので、私はログインしたくない。そのために私はクッキーのために以下のコードを実装しました。PythonとGoogle App Engineを使用したCookie

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ファイルのヘッダーに見える:

なし 状況私は、次のコードを使用していた上記のコードをテストするには

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)) 

:200 OK コンテンツタイプ:text/html; charset = utf-8 キャッシュ制御:no-cache セットクッキー:MyCookie = NewValue; expires = Thu、2012年12月6日17:55:41 GMT; Path =/ コンテンツの長さ:1199

上記の「なし」はコードの「値1」を示します。

ヘッダーに追加されている場合でも、Cookieの値が「なし」である理由を教えていただけますか?

ご協力いただきありがとうございます。

答えて

3

set_cookie()に電話すると、準備中の応答にCookieが設定されます(つまり、応答が送信された後、関数が返された後にCookieが設定されます)。その後のget_cookie()の呼び出しは、現在の要求のヘッダーからの読み取りです。現在のリクエストには、テストしているクッキーセットがないため、読み込まれません。しかし、このページに再度アクセスする場合は、クッキーがリクエストの一部になるので別の結果が得られるはずです。

+0

ありがとうございます。残念ながら、私はページを見直したときに別の結果を得られません。私は他の提案のために開いていますか? – Maal

+0

申し訳ありません。私はちょうどあなたが100%正しいことに気づいた。どうもありがとうございました。 – Maal

関連する問題