我有一個應用程序使用django.contrib.auth但不使用Django的內置權限系統。相反,視圖具有@login_required裝飾器,然後檢查用戶屬於哪個組,並根據組遵循不同的代碼執行分支。Django中間件在會話中確定用戶組
用戶只能屬於一個組。
每次檢查用戶組似乎太多了,所以我正在嘗試編寫一個Django中間件,它可以讓我在會話中知道用戶的組。
看看下面的代碼,我的中間件能像我想要的那樣工作嗎?
class SetGroupMiddleware(object):
def process_request(self, request):
check_if_already_set = request.session.get('thegroup', 'notset')
if check_if_already_set == 'notset':
if request.user.id: # User is not AnonymousUser
groups = request.user.groups.all()
if groups: # actually this will always be True
request.session['thegroup'] = str(groups[0].name) # flowchart of the app ensures that the logged in user will only have one group, and that the user will always have a group
else:
request.session['thegroup'] = 'nogroup' # for completeness
然後我打算在需要的地方檢查request.session ['thegroup']。
需要您的建議和意見。如果以這種方式處理會話是否安全?這會工作嗎?我是Django,Python和編程的新手。
謝謝。
因此,如果SessioonMiddleware在此之後去,我明確地需要標記會話髒?或者會話框架會自動檢測並保存這些信息? – gbsmith 2009-12-11 20:18:03
因爲你直接修改會話,所以你不需要明確地保存它。請參閱:http://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessions-are-saved – 2009-12-11 20:22:35