Cookies using Python and Google App Engine

2024/9/22 18:31:16

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 defaultdef 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 stuffraise ValueError("Invalid cookie %r:%r" % (name,value))new_cookie = Cookie.BaseCookie()new_cookie[name] = valueif domain:new_cookie[name]["domain"] = domainif 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"] = pathfor 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

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

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

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

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

Your help is very much appreciated.

Answer

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.

https://en.xdnf.cn/q/71917.html

Related Q&A

Matplotlib animations - how to export them to a format to use in a presentation?

So, I learned how to make cute little animations in matplotlib. For example, this:import numpy as np import matplotlib import matplotlib.pyplot as pltplt.ion()fig = plt.figure() ax = fig.add_subplot(…

Where is python interpreter located in virtualenv?

Where is python intrepreter located in virtual environment ? I am making a GUI project and I stuck while finding the python interpreter in my virtual environment.

Tkinter check which Entry last had focus

I am working on a program that has a virtual keyboard I created using Tkinter. The pages that have the keyboard enabled have entry widgets where the users need to input data. I am using pyautogui as …

Python Popen grep

Id like Popen to execute:grep -i --line-buffered "grave" data/*.txtWhen run from the shell, this gives me the wanted result. If I start, in the very same directory where I test grep, a python…

Url structure and form posts with Flask

In Flask you write the route above the method declaration like so: @app.route(/search/<location>/) def search():return render_template(search.html)However in HTML the form will post to the url in…

How can I simulate a key press in a Python subprocess?

The scenario is, I have a Python script which part of it is to execute an external program using the code below:subprocess.run(["someExternalProgram", "some options"], shell=True)An…

Difference between pd.merge() and dataframe.merge()

Im wondering what the difference is when you merge by pd.merge versus dataframe.merge(), examples below:pd.merge(dataframe1, dataframe2)anddataframe1.merge(dataframe2)

ctypes in python crashes with memset

I am trying to erase password string from memory like it is suggested in here.I wrote that little snippet:import ctypes, sysdef zerome(string):location = id(string) + 20size = sys.getsizeof(string)…

Python __del__ does not work as destructor? [duplicate]

This question already has answers here:What is the __del__ method and how do I call it?(5 answers)Closed 4 years ago.After checking numerous times, I did find inconsistent info about the topic.In some…

How to set default button in PyGTK?

I have very simple window where I have 2 buttons - one for cancel, one for apply. How to set the button for apply as default one? (When I press enter, "apply" button is pressed)However, I wa…