您需要做的就是decorate
您想要保护的视图,如下所示:
@staff_member_required
def staff_users(request):
....
# some logic
return HttpResponseRedirect('/repositories/')
如果您想要一个自定义逻辑来测试而不是使用 django 装饰器,那么您也可以编写自己的装饰器。
def staff_users_only(function):
def wrap(request, *args, **kwargs):
profile = request.session['user_profile']
if profile is True: #then its a staff member
return function(request, *args, **kwargs)
else:
return HttpResponseRedirect('/')
wrap.__doc__=function.__doc__
wrap.__name__=function.__name__
return wrap
并将其用作:
@staff_users_only
def staff_users(request):
....
# some logic
return HttpResponseRedirect('/repositories/')
编辑
用于测试的请求对象上的会话关联可以如下完成:
def test_request_object(self):
self.user = User.objects.create_user(
username='abc', email='abc@gmail.com', password='1234')
request = HttpRequest()
#create a session which will hold the user profile that will be used in by our custom decorator
request.session = {} #Session middleware is not available in UnitTest hence create a blank dictionary for testing purpose
request.session['user_profile'] = self.user.is_staff #assuming its django user.
# User send a request to access repositories
response = staff_users(request)
#Check the response type for appropriate action
self.assertIsNone(response)
编辑 2
Client
使用 django库进行测试也是一个更好的主意:
>>> from django.test import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'abc', 'password': '1234'})
>>> response.status_code
200
>>> response = c.get('/user/protected-page/')
>>> response.content
b'<!DOCTYPE html...