Login

Another Cookieless Session Middleware

Author:
lvscar
Posted:
June 1, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

the snippet improve juliocarlos's greate works(see http://www.djangosnippets.org/snippets/1235/ ) ,merge functtions to one middlewere class, fixed url regular expression and eliminate AJAX support etc...

it's tested with django 1.0.2 and work fine on my wap site.

  • the middlewere must before SessionMiddlewar in MIDDLEWARE_CLASSES tuple eg:

MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'middleware.cookieless_session.CookielessSessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#-*- coding:utf-8 -*-
from django.http  import  HttpResponseRedirect
import re,pdb

class CookielessSessionMiddleware(object):
    def __init__(self):

        self._re_links = re.compile(r'<a(?P<pre_href>[^>]*?)href=["\'](?P<in_href>[^"\']*?)(?P<anchor>#\S+)?["\'](?P<post_href>[^>]*?)>', re.I)

        self._re_forms = re.compile('</form>', re.I)

    def _prepare_url(self, url):
        patt = None
        if url.find('?') == -1:
            patt = '%s?'
        else:
            patt = '%s&amp;'
        return patt % (url,)

    def process_request(self, request):
        if not request.COOKIES.has_key('sessionid'):
            value = None
            if hasattr(request, 'POST') and request.POST.has_key('sessionid'):
                value = request.POST['sessionid']
            elif hasattr(request, 'GET') and request.GET.has_key('sessionid'):
                value = request.GET['sessionid']
            if value:
                request.COOKIES['sessionid'] = value        

    def process_response(self, request, response):

        if not request.path.startswith("/admin")  and response.cookies.has_key('sessionid'):
            try:
                sessionid = response.cookies['sessionid'].coded_value
                if type(response) is HttpResponseRedirect:

                    if not sessionid: sessionid = ""
                    redirect_url = [x[1] for x in response.items() if x[0] == "Location"][0]
                    redirect_url = self._prepare_url(redirect_url)
                    return HttpResponseRedirect('%ssessionid=%s' % (redirect_url,sessionid,)) 


                def new_url(m):
                    anchor_value = ""
                    if m.groupdict().get("anchor"): anchor_value = m.groupdict().get("anchor")
                    return_str = '<a%shref="%ssessionid=%s%s"%s>' % \
                         (m.groupdict()['pre_href'],
                         self._prepare_url(m.groupdict()['in_href']),
                         sessionid,
                         anchor_value,
                         m.groupdict()['post_href'])
                    return return_str                                 
                response.content = self._re_links.sub(new_url, response.content)


                repl_form = '<div><input type="hidden" name="sessionid" value="%s" /></div>' + \
                    '</form>'
                repl_form = repl_form % (sessionid,)
                response.content = self._re_forms.sub(repl_form, response.content)

                return response
            except:

                return response
        else:
            return response        

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.