我们从Python开源项目中,提取了以下4个代码示例,用于说明如何使用rest_framework.authentication.BasicAuthentication()。
def get_authentication_introspectors(view): """ Get View Authentication Introspectors :param view: DjangoRestFramework View :return: list of authentication introspectors :rtype: list """ from rest_framework import authentication authenticators_map = { authentication.BasicAuthentication: BasicAuthenticationIntrospector, authentication.TokenAuthentication: TokenAuthenticationIntrospector, } authenticators = getattr(view, 'authentication_classes', []) introspectors = [] for authenticator in authenticators: introspectors.append( authenticators_map.get(authenticator, BaseAuthenticationIntrospector)(authenticator) ) return introspectors
def test_user_list_with_basic_and_digest(self): view = ConnectViewSet.as_view( {'get': 'list'}, authentication_classes=( DigestAuthentication, authentication.BasicAuthentication )) request = self.factory.get('/') auth = BasicAuth('bob', 'bob') request.META.update(auth(request.META)) request.session = self.client.session response = view(request) self.assertEqual(response.status_code, 401) self.assertEqual(response.data['detail'], u"Invalid username/password") auth = BasicAuth('bob', 'bobbob') request.META.update(auth(request.META)) request.session = self.client.session response = view(request) temp_token = TempToken.objects.get(user__username='bob') self.data['temp_token'] = temp_token.key self.assertEqual(response.status_code, 200) self.assertEqual(response.data, self.data)
def test_user_list_with_basic_and_digest(self): view = ConnectViewSet.as_view( {'get': 'list'}, authentication_classes=( DigestAuthentication, authentication.BasicAuthentication )) request = self.factory.get('/') auth = BasicAuth('bob', 'bob') request.META.update(auth(request.META)) request.session = self.client.session response = view(request) self.assertEqual(response.status_code, 401) self.assertEqual(response.data['detail'], u"Invalid username/password.") auth = BasicAuth('bob', 'bobbob') # redo the request request = self.factory.get('/') request.META.update(auth(request.META)) request.session = self.client.session response = view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, self.data)
def get_settings(): """Due to app loading issues during startup provide a function to return settings only when needed.""" # Import late because apps may not be loaded yet from rest_framework.authentication import SessionAuthentication, BasicAuthentication return getattr(settings, "REST_FRAMEWORK_EXTRAS", { "blacklist": { "sessions-session": {}, "admin-logentry": {}, }, "authentication-classes": (SessionAuthentication, BasicAuthentication), "permission-classes": (DjangoModelPermissions,) })