本文整理汇总了Python中rest_framework.exceptions.NotAuthenticated方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NotAuthenticated方法的具体用法?Python exceptions.NotAuthenticated怎么用?Python exceptions.NotAuthenticated使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.NotAuthenticated方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _which_user
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def _which_user(self, request):
"""
Determine the user from `request`, allowing superusers to specify
another user by passing the `username` query parameter
"""
if request.user.is_anonymous:
raise exceptions.NotAuthenticated()
if 'username' in request.query_params:
# Allow superusers to get others' tokens
if request.user.is_superuser:
user = get_object_or_404(
User,
username=request.query_params['username']
)
else:
raise exceptions.PermissionDenied()
else:
user = request.user
return user
示例2: handle_exception
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
"""
if isinstance(exc, (exceptions.NotAuthenticated,
exceptions.AuthenticationFailed)):
# WWW-Authenticate header for 401 responses, else coerce to 403
auth_header = self.get_authenticate_header(self.request)
if auth_header:
exc.auth_header = auth_header
else:
exc.status_code = status.HTTP_403_FORBIDDEN
exception_handler = self.get_exception_handler()
context = self.get_exception_handler_context()
response = exception_handler(exc, context)
if response is None:
self.raise_uncaught_exception(exc)
response.exception = True
return response
示例3: perform_create
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def perform_create(self, serializer):
user = self.request.user
if not user.is_authenticated:
raise NotAuthenticated()
serializer.save(reporter=user)
示例4: _vote
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def _vote(self, request, pk, options):
user = request.user
if not user.is_authenticated:
raise NotAuthenticated()
vote, _ = LinkVote.objects.get_or_create(
link_id=pk,
voter=user,
defaults=options,
)
for name, value in options.items():
setattr(vote, name, value)
vote.save()
serializer = LinkSerializer(instance=vote.link)
return Response(serializer.data)
示例5: raise_exception_treat
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def raise_exception_treat(func):
@functools.wraps(func)
def inner(self, request, *args, **kwargs):
try:
return func(self, request, *args, **kwargs)
except ValidationError, error:
log.error(error)
raise rest_exceptions.ValidationExceptionJson(error)
except (exceptions_api.APIException, exceptions_api.AuthenticationFailed,
exceptions_api.MethodNotAllowed, exceptions_api.NotAcceptable,
exceptions_api.NotAuthenticated, exceptions_api.ParseError,
exceptions_api.PermissionDenied, exceptions_api.Throttled,
exceptions_api.UnsupportedMediaType, rest_exceptions.ValidationAPIException), error:
log.error(error)
raise error
示例6: custom_exception_handler
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def custom_exception_handler(exc, context):
# if its a view with a list and request attr
if 'view' in context and hasattr(context['view'], 'list') and hasattr(context['view'], 'request'):
view = context['view']
request = view.request
if request.method == 'GET' and settings.ENABLE_UNAUTHENTICATED_RESULTS and isinstance(exc, NotAuthenticated):
return view.list(context['request'])
return exception_handler(exc, context)
示例7: create
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def create(self, request, *args, **kwargs):
if self.request.user.is_anonymous:
raise exceptions.NotAuthenticated()
itask_data = {
'library': request.POST.get('library') not in ['false', False],
# NOTE: 'filename' here comes from 'name' (!) in the POST data
'filename': request.POST.get('name', None),
'destination': request.POST.get('destination', None),
}
if 'base64Encoded' in request.POST:
encoded_str = request.POST['base64Encoded']
encoded_substr = encoded_str[encoded_str.index('base64') + 7:]
itask_data['base64Encoded'] = encoded_substr
elif 'file' in request.data:
encoded_xls = to_str(base64.b64encode(request.data['file'].read()))
itask_data['base64Encoded'] = encoded_xls
if 'filename' not in itask_data:
itask_data['filename'] = request.data['file'].name
elif 'url' in request.POST:
itask_data['single_xls_url'] = request.POST['url']
import_task = ImportTask.objects.create(user=request.user,
data=itask_data)
# Have Celery run the import in the background
import_in_background.delay(import_task_uid=import_task.uid)
return Response({
'uid': import_task.uid,
'url': reverse(
'importtask-detail',
kwargs={'uid': import_task.uid},
request=request),
'status': ImportTask.PROCESSING
}, status.HTTP_201_CREATED)
示例8: hash
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def hash(self, request):
"""
Creates an hash of `version_id` of all accessible assets by the user.
Useful to detect changes between each request.
:param request:
:return: JSON
"""
user = self.request.user
if user.is_anonymous:
raise exceptions.NotAuthenticated()
else:
accessible_assets = get_objects_for_user(
user, "view_asset", Asset).filter(asset_type=ASSET_TYPE_SURVEY) \
.order_by("uid")
assets_version_ids = [asset.version_id for asset in accessible_assets if asset.version_id is not None]
# Sort alphabetically
assets_version_ids.sort()
if len(assets_version_ids) > 0:
hash = md5(hashable_str("".join(assets_version_ids))).hexdigest()
else:
hash = ""
return Response({
"hash": hash
})
示例9: permission_denied
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def permission_denied(self, request, message=None):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if request.authenticators and not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=message)
示例10: create
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotAuthenticated [as 别名]
def create(self, request, *args, **kwargs):
if self.request.user.is_anonymous:
raise exceptions.NotAuthenticated()
# Read valid options from POST data
valid_options = (
'type',
'source',
'group_sep',
'lang',
'hierarchy_in_labels',
'fields_from_all_versions',
)
task_data = {}
for opt in valid_options:
opt_val = request.POST.get(opt, None)
if opt_val is not None:
task_data[opt] = opt_val
# Complain if no source was specified
if not task_data.get('source', False):
raise exceptions.ValidationError(
{'source': 'This field is required.'})
# Get the source object
source_type, source = _resolve_url_to_asset_or_collection(
task_data['source'])
# Complain if it's not an Asset
if source_type != 'asset':
raise exceptions.ValidationError(
{'source': 'This field must specify an asset.'})
# Complain if it's not deployed
if not source.has_deployment:
raise exceptions.ValidationError(
{'source': 'The specified asset must be deployed.'})
# Create a new export task
export_task = ExportTask.objects.create(user=request.user,
data=task_data)
# Have Celery run the export in the background
export_in_background.delay(export_task_uid=export_task.uid)
return Response({
'uid': export_task.uid,
'url': reverse(
'exporttask-detail',
kwargs={'uid': export_task.uid},
request=request),
'status': ExportTask.PROCESSING
}, status.HTTP_201_CREATED)