views:

12

answers:

1

I'm using a web service backend to provide authentication to Django, and the get_user method must retain a cookie provided by the web service in order to associate with a session. Right now, I make my remote calls just by calling urllib2.urlopen(myTargetService) but this doesn't pass the cookie for the current session along.

I have created a session access middleware to store the session in the settings:

class SessionAccessMiddleware:

  def process_request(self, request):
    settings.current_session = request.session

So, I can access the request session in get_request and post_request, but I don't know how to have urllib2 remember my cookies in a session-specific way.

How do I do this?

A: 

Here: http://docs.python.org/library/cookielib.html#examples are examples of doing exactly what you try to do with urllib2 and cookielib. So according to docs you need to create cookielib.CookieJar, set cookie with correct data (from session), build an opener that uses your CookieJar and use it to fetch yourTargetService.

If settings in your middleware code means from django.conf import settings it's not good idea. Look at http://github.com/svetlyak40wt/django-globals/ for a place where you can safely store request-wide data for access from somewhere where request object is unaccessible. Also, it would be probably good idea to write custom authentication backend and use it with django.contrib.auth - instead of rolling your own auth system from scratch - which is covered here: http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend .

cji
I have, in fact, written a custom auth backend that is using these, so we're good with that.django-globals doesn't seem to add much to the party; I'll consider it, if settings ever gives me trouble.The thing I don't fully understand is the opener; how long can I keep those around? Can I create one and store _that_ in the session, for example?
Chris R
I just checked - it appears you can not, sorry. opener and cookiejar objects are not pickleable(`UnpickleableError: Cannot pickle <type 'thread.lock'> objects`), so they can't be stored in sessions. But it is possible to pickle Cookie, as I just found out, so you can store it and add it to CookieJar (with `set_cookie`) every time you create an opener.
cji