无cookie环境实现django会话

django的会话(session)中间件不提供类似j2ee和php中基于url重写的会话机制。
[quote]
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.
[/quote]

以下脚本通过中间件为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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值