Next up we'll use Python's 'Cookie' module to do a little baking! (Ironically I suck at making real cookies.)
Ok, you have to agree, setting cookies couldn't be much simpler, and the 'Cookie' module wraps it up nicely. The difficulty comes when you want to retrieve your values... ok maybe I'm exaggerating a little here.
This is all about parsing the 'HTTP_COOKIE' header and inserting the cookie values into a dictionary. We start by importing the 'os' module into our program and defining the monster() function -- this checks if the 'cookies' string exists or not. If it does then we split it, leaving us with a list of 'key=value' strings. After that all we have left to do is loop over the list and split the values again, placing them into the dictionary. Ok finally let's do something a little useful with our cookies... and in keeping with our final example, we're going to create a counter function, which allows you to set limits on different processes. Observe and enjoy.
The start of this is exactly the same as in our monster() function except that if there are no cookies set, then we create one and set its value to one. If there are any cookies to unpack, then we check for 'count' in the handler dictionary and type-cast its value to a 'number' using int()... 'number' is then compared to the 'count' variable to check if the user is under or over their limit. Provided they're under their limit, then we update the cookie and set the expiry date to 24 hours before returning True; this is done so we can use if-else blocks to control the users access.
blog comments powered by Disqus |