2

I am creating a webapp on facebook that allows users to provide login details for a third party website and make requests via my app to that service. (i.e. they have an account with my app, and an account with the 3rd party website.)

There is no API for this third party website, so I am using URLlib to perform the logins. Furthermore, all interactions with this 3rd party app are via a Celery Queue, so there is no link between the frontend of my app, and the actual request from my app to the 3rd party

I am trying to come up with the best way to deal with managing the cookies returned by the third party website so that I don't have to log the user in at every action.

Would it be madness to create a table that maps users to cookies and serialise the cookies into the database?

2 Answers 2

1

For anyone who happens across this in the future, I was able to save the cookies in the database by using cookielib (a part of urllib) and creating my own cookiejar that dumps and loads cookies as strings that can be saved in a DB:

class StringCookieJar(cookielib.CookieJar):
    def __init__(self, cookie_string="", policy=None):
        cookielib.CookieJar.__init__(self, policy)
            if cookie_string:
                self._cookies = pickle.loads(cookie_string)
    def dump(self):
            return pickle.dumps(self._cookies)

When creating an instance of my connection object, I set up the urllib opener with my custom cookielib:

self.cookiejar = StringCookieJar(cookie_string=str(self.account.cookies))
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))

where self.account.cookies is the field in the database I am using to store my cookie string:

cookies = models.CharField(max_length=2000, blank=True)
1

Expanding on the answer above:

class MyConnection(models.Model):
    cookie_text = models.TextField(blank=True, null=True, editable=False)

    def __init__(self, *args, **kwargs):
        self.cookie_jar = StringCookieJar(self.cookies)

    def save(self, *args, **kwargs):
        self.cookies = self.cookie_jar.dump()
        return super(Connection, self).save(*args, **kwargs)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.