views:

962

answers:

4

I'd like to set a cookie via Django with that has several different values to it, similar to .NET's HttpCookie.Values property. Looking at the documentation, I can't tell if this is possible. It looks like it just takes a string, so is there another way?

I've tried passing it an array ([10, 20, 30]) and dictionary ({'name': 'Scott', 'id': 1}) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.

+5  A: 

.NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem.

I will say that you're doing the right thing, in not using multiple cookies. Keep the over-the-wire overhead down by doing what you're doing.

foxxtrot
A: 

Django does not support it. The best way would be to separate the values with arbitrary separator and then just split the string, like you already said.

ak
A: 

If you're looking for something a little more abstracted, try using sessions. I believe the way they work is by storing an id in the cookie that matches a database record. You can store whatever you want in it. It's not exactly the same as what you're looking for, but it could work if you don't mind a small amount of db overhead.

defrex
A: 

(Late answer!)

This will be bulkier, but you call always use python's built in serializing.

You could always do something like:

import pickle
class MultiCookie():
    def __init__(self,cookie=None,values=None):
        if cookie != None:
            try:
                self.values = pickle.loads(cookie)
            except:
                # assume that it used to just hold a string value
                self.values = cookie
        elif values != None:
            self.values = values
        else:
            self.values = None

    def __str__(self):
        return pickle.dumps(self.values)

Then, you can get the cookie:

newcookie = MultiCookie(cookie=request.COOKIES.get('multi'))
values_for_cookie = newcookie.values

Or set the values:

mylist = [ 1, 2, 3 ]
newcookie = MultiCookie(values=mylist)
request.set_cookie('multi',value=newcookie)
Jordan Reiter