mirror of
https://github.com/ansible/awx.git
synced 2026-04-04 09:45:06 -02:30
Permissions-related updates and fixes, more tests, better handling of any user input that would previously generate a server error.
This commit is contained in:
54
awx/main/utils.py
Normal file
54
awx/main/utils.py
Normal file
@@ -0,0 +1,54 @@
|
||||
# Python
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
|
||||
# Django
|
||||
from django.conf import settings
|
||||
from django.shortcuts import _get_queryset
|
||||
|
||||
# Django REST Framework
|
||||
from rest_framework.exceptions import ParseError, PermissionDenied
|
||||
|
||||
__all__ = ['get_object_or_400', 'get_object_or_403', 'camelcase_to_underscore']
|
||||
|
||||
def get_object_or_400(klass, *args, **kwargs):
|
||||
'''
|
||||
Return a single object from the given model or queryset based on the query
|
||||
params, otherwise raise an exception that will return in a 400 response.
|
||||
'''
|
||||
queryset = _get_queryset(klass)
|
||||
try:
|
||||
return queryset.get(*args, **kwargs)
|
||||
except queryset.model.DoesNotExist, e:
|
||||
raise ParseError(*e.args)
|
||||
except queryset.model.MultipleObjectsReturned, e:
|
||||
raise ParseError(*e.args)
|
||||
|
||||
def get_object_or_403(klass, *args, **kwargs):
|
||||
'''
|
||||
Return a single object from the given model or queryset based on the query
|
||||
params, otherwise raise an exception that will return in a 403 response.
|
||||
'''
|
||||
queryset = _get_queryset(klass)
|
||||
try:
|
||||
return queryset.get(*args, **kwargs)
|
||||
except queryset.model.DoesNotExist, e:
|
||||
raise PermissionDenied(*e.args)
|
||||
except queryset.model.MultipleObjectsReturned, e:
|
||||
raise PermissionDenied(*e.args)
|
||||
|
||||
def camelcase_to_underscore(s):
|
||||
'''
|
||||
Convert CamelCase names to lowercase_with_underscore.
|
||||
'''
|
||||
s = re.sub(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', s)
|
||||
return s.lower().strip('_')
|
||||
|
||||
class RequireDebugTrueOrTest(logging.Filter):
|
||||
'''
|
||||
Logging filter to output when in DEBUG mode or running tests.
|
||||
'''
|
||||
|
||||
def filter(self, record):
|
||||
return settings.DEBUG or 'test' in sys.argv
|
||||
Reference in New Issue
Block a user