浏览 3332 次
锁定老帖子 主题:无cookie环境实现django会话
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
|
|
---|---|
作者 | 正文 |
发表时间:2009-06-01
最后修改:2009-06-02
引用 Session IDs in URLs The Django sessions framework is entirely, and solely, cookie-based. It does not fall back to putting session IDs in URLs as a last resort, as PHP does. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. 以下脚本通过中间件为django增添无cookie时的会话支持,在django1.0.2版本下工作正常, 注意,该中间件在setting模块MIDDLEWARE_CLASSES tuple中的位置必须优先于SessionMiddleware #-*- 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&' 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 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-11-12
感觉还可以啊。
|
|
返回顶楼 | |