本文整理汇总了Python中rest_framework.response.Response类的典型用法代码示例。如果您正苦于以下问题:Python Response类的具体用法?Python Response怎么用?Python Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: response_or_404
def response_or_404(self, query_result, many=False):
response = Response()
if query_result is None:
response.status_code = 404
else:
response.data = self.serializer_class(query_result, many=many)
return response
示例2: exception_handler
def exception_handler(exc, context):
response = rest_exception_handler(exc, context)
if response is None:
if hasattr(exc, "name") and callable(exc.name):
name = exc.name()
else:
name = exc.__class__.__name__
response = {
"detail": str(exc),
"name": name
}
if settings.DEBUG:
import traceback
response['traceback'] = traceback.format_tb(exc.__traceback__)
response = Response(response)
else:
response.data["name"] = exc.__class__.__name__
response.status_code = 500
return response
示例3: post
def post(self, request):
print
"creating a goddamned user"
print
request.DATA
print
dir(request)
username = request.DATA.get('username', '')
password = request.DATA.get('password', '')
email = request.DATA.get('email', '')
print
username
user = User.objects.create_user(username, email, password)
user = authenticate(username=username, password=password)
cl = Client.objects.create(user=user, name=username,
redirect_uri="http://localhost/",
client_type=2
)
token = AccessToken.objects.create(user=user, client=cl,
expires=datetime.date(year=2015, month=1, day=2)
)
if self.request.accepted_renderer.format == 'json':
response = Response({'access_token': token.token})
response.status_code = status.HTTP_201_CREATED
return response
login(request, user)
return redirect('/users/' + str(user.id))
示例4: get
def get(self, request, offset=0, limit=10, orderBy='id', order='asc', filterOn=None, filterValue=None,format=None):
if offset is None:
offset = 0
if limit is None:
limit = 10
if orderBy == None:
orderBy = 'id'
if order == 'desc':
orderBy = '-' + orderBy
try:
if filterOn is None or filterValue is None:
users = Users.objects.all().order_by(orderBy)[offset:limit]
count = Users.objects.all()[offset:limit].count()
else:
users = Users.objects.all().filter(**{ filterOn: filterValue }).order_by(orderBy)[offset:limit]
count = Users.objects.all().filter(**{ filterOn: filterValue })[offset:limit].count()
total_count = Users.objects.count()
serializer = UserDetailListViewSerializer(users, many=True)
response = Response()
response['count'] = count
response['total_count'] = total_count
response.data = serializer.data
response.status = status.HTTP_200_OK
return response
except Users.DoesNotExist:
return Response(status=status.HTTP_400_BAD_REQUEST)
示例5: get
def get(self, request, *args, **kw):
ip = args[0]
details_request = IPDetails(ip, *args, **kw)
result = DetailsSerializer(details_request)
response = Response(result.data, status=status.HTTP_200_OK)
visit = Visit()
visit.endpoint = '/api/details/' + ip
visit.timestamp = get_epoch_timestamp()
visit.address = get_ip(request)
cookie = request.COOKIES.get("alienvaultid", None)
if cookie is None:
ck_val = create_random_string()
# set this cookie to expire in one year
response.set_cookie('alienvaultid', ck_val, max_age=31536000)
visitor = Visitor()
visitor.alienvaultid = ck_val
visitor.save()
else:
visitor = Visitor.objects.get(alienvaultid=cookie)
visit.visitor_id = visitor.id
visit.save()
return response
示例6: post
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
user = serializer.object.get('user') or request.user
token = serializer.object.get('token')
response_data = jwt_response_payload_handler(token, user, request)
response = Response(response_data)
response.data = {
'token': token,
'user':{
'alias': user.alias,
'email': user.email
}
}
if api_settings.JWT_AUTH_COOKIE:
expiration = (datetime.utcnow() +
api_settings.JWT_EXPIRATION_DELTA)
response.set_cookie(api_settings.JWT_AUTH_COOKIE,
token,
expires=expiration,
httponly=True)
return response
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例7: post
def post(self, request, assembly, format=None):
respmsg = "inicio"
try:
api = get_api_obj(assembly)
api.ignore_admin_user = "true"
api.social_ideation_source = request.data['source'] # indicates the name of the providerId (e.g., social_ideation_facebook)
api.social_ideation_source_url = request.data['source_url'] # source to the original post
api.social_ideation_user_source_url = request.data['user_url'] # link to the user
api.social_ideation_user_source_id = request.data['user_external_id'] # email or id of the user in the source social network
api.social_ideation_user_name = request.data['user_name'] # the name of the author in the social network
api.assembly_id = assembly.appcivist_id
new_obj_raw = getattr(api, self.api_method)(**self.api_method_params)
new_obj_id = find_obj_id(new_obj_raw)
new_obj= self.create_obj(new_obj_id, assembly, new_obj_raw)
serializer = self.serializer_class(new_obj)
if self.filters:
new_obj.sync = True
new_obj.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
except Exception as e:
resp = Response(status=status.HTTP_400_BAD_REQUEST)
resp.content = e
return resp
示例8: get_response
def get_response(self):
serializer_class = self.get_response_serializer()
if getattr(settings, 'REST_USE_JWT', False):
data = {
'user': self.user,
'token': self.token
}
serializer = serializer_class(instance=data,
context={'request': self.request})
else:
serializer = serializer_class(instance=self.token,
context={'request': self.request})
response = Response(serializer.data, status=status.HTTP_200_OK)
if getattr(settings, 'REST_USE_JWT', False):
from rest_framework_jwt.settings import api_settings as jwt_settings
if jwt_settings.JWT_AUTH_COOKIE:
from datetime import datetime
expiration = (datetime.utcnow() + jwt_settings.JWT_EXPIRATION_DELTA)
response.set_cookie(jwt_settings.JWT_AUTH_COOKIE,
self.token,
expires=expiration,
httponly=True)
return response
示例9: custom_exception_handler
def custom_exception_handler(exc):
"""
Formats REST exceptions like:
{
"error": "error_code",
"error_description": "description of the error",
}
:param exc: Exception
:return: Response
"""
response = exception_handler(exc)
if not response:
# Unhandled exceptions (500 internal server errors)
response = Response(data={
'error': 'server_error',
'error_description': unicode(exc),
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return response
if hasattr(exc, 'default_error'):
response.data['error'] = exc.default_error
else:
response.data['error'] = 'api_error'
if hasattr(exc, 'default_detail'):
response.data['error_description'] = exc.default_detail
elif 'detail' in response.data:
response.data['error_description'] = response.data['details']
if 'detail' in response.data:
del response.data['detail']
return response
示例10: datal_exception_handler
def datal_exception_handler(exception, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exception, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status'] = response.status_code
if not 'description' in response.data:
response.data['description'] = ''
if 'detail' in response.data:
response.data['description'] = response.data.pop('detail')
response.data['error'] = str(exception.__class__.__name__)
response.data['type'] = 'api-error'
elif isinstance(exception, DATALException):
set_rollback()
response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
response.data['status'] = exception.status_code
response.data['description'] = exception.description % {}
response.data['error'] = str(exception.__class__.__name__)
response.data['type'] = exception.tipo
elif not settings.DEBUG:
logger = logging.getLogger(__name__)
trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
logger.error('[UnexpectedCatchError] %s. %s %s' % (
str(exception), repr(exception), trace))
set_rollback()
response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
response.data['status'] = response.status_code
response.data['description'] = str(exception)
response.data['error'] = str(exception.__class__.__name__)
response.data['type'] = 'unexpected-error'
return response
示例11: create
def create(self, request):
"""Override request to handle kicking off celery task"""
indicators_config = OTIIndicatorsConfig.objects.all()[0]
failures = []
for attr in ['poverty_line', 'nearby_buffer_distance_m',
'max_commute_time_s', 'avg_fare', 'arrive_by_time_s']:
if not indicators_config.__getattribute__(attr) > 0:
failures.append(attr)
if not valid_sample_periods():
failures.append('sample_periods')
try:
with connection.cursor() as c:
c.execute('''SELECT COUNT(*) FROM planet_osm_line''')
except ProgrammingError:
failures.append('osm_data')
if len(failures) > 0:
response = Response({'error': 'Invalid configuration',
'items': failures})
response.status_code = status.HTTP_400_BAD_REQUEST
return response
response = super(IndicatorJobViewSet, self).create(request)
if response.status_code == status.HTTP_201_CREATED:
start_indicator_calculation.apply_async(args=[self.object.id], queue='indicators')
return response
示例12: test_should_return_response_from_cache_if_it_is_in_it
def test_should_return_response_from_cache_if_it_is_in_it(self):
def key_func(**kwargs):
return 'cache_response_key'
class TestView(views.APIView):
@cache_response(key_func=key_func)
def get(self, request, *args, **kwargs):
return Response(u'Response from method 4')
view_instance = TestView()
view_instance.headers = {}
cached_response = Response(u'Cached response from method 4')
view_instance.finalize_response(request=self.request, response=cached_response)
cached_response.render()
response_dict = (
cached_response.rendered_content,
cached_response.status_code,
cached_response._headers
)
self.cache.set('cache_response_key', response_dict)
response = view_instance.dispatch(request=self.request)
self.assertEqual(
response.content.decode('utf-8'),
u'"Cached response from method 4"')
示例13: get
def get(self, request, *args, **kwargs):
contextdata = {
"@context": getHydraVocab()
}
response = Response(data=contextdata)
if request.accepted_media_type != "text/html":
response.content_type = "application/ld+json"
return response
示例14: get
def get(self, request, doc=None):
if doc.endswith('.js'):
doc = doc.replace(".js", "-js")
version = MarkdownType.get_default()
response = Response({})
response['Location'] = "/%s/docs/%s" % (version.name, doc)
response.status_code = status.HTTP_302_FOUND
return response
示例15: handle_exception
def handle_exception(self, exc):
# REST API drops the string attached to Django's PermissionDenied
# exception, and replaces it with a generic "Permission Denied"
if isinstance(exc, DjangoPermissionDenied):
response=Response({'detail': {"error": "PermissionDenied", "specific_error": str(exc), "fields": {}}}, status=status.HTTP_403_FORBIDDEN)
response.exception=True
return response
else:
return super(XOSListCreateAPIView, self).handle_exception(exc)