本文整理汇总了Python中rest_framework.status.HTTP_500_INTERNAL_SERVER_ERROR属性的典型用法代码示例。如果您正苦于以下问题:Python status.HTTP_500_INTERNAL_SERVER_ERROR属性的具体用法?Python status.HTTP_500_INTERNAL_SERVER_ERROR怎么用?Python status.HTTP_500_INTERNAL_SERVER_ERROR使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类rest_framework.status
的用法示例。
在下文中一共展示了status.HTTP_500_INTERNAL_SERVER_ERROR属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_list_cost_model_rate_rbac_access
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def test_list_cost_model_rate_rbac_access(self):
"""Test GET /cost-models with an rbac user."""
user_data = self._create_user_data()
customer = self._create_customer_data()
request_context = self._create_request_context(customer, user_data, create_customer=True, is_admin=False)
self.initialize_request(context={"request_context": request_context, "user_data": user_data})
test_matrix = [
{"access": {"rate": {"read": [], "write": []}}, "expected_response": status.HTTP_403_FORBIDDEN},
{"access": {"rate": {"read": ["*"], "write": []}}, "expected_response": status.HTTP_200_OK},
{
"access": {"rate": {"read": ["not-a-uuid"], "write": []}},
"expected_response": status.HTTP_500_INTERNAL_SERVER_ERROR,
},
]
client = APIClient()
for test_case in test_matrix:
with patch.object(RbacService, "get_access_for_user", return_value=test_case.get("access")):
url = reverse("cost-models-list")
caches["rbac"].clear()
response = client.get(url, **request_context["request"].META)
self.assertEqual(response.status_code, test_case.get("expected_response"))
示例2: custom_exception_handler
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if not response:
if isinstance(exc, (SafeServiceException, SafeCreationServiceException, TransactionServiceException,
FundingServiceException)):
response = Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)
else:
response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
if str(exc):
exception_str = '{}: {}'.format(exc.__class__.__name__, exc)
else:
exception_str = exc.__class__.__name__
response.data = {'exception': exception_str}
logger.warning('%s - Exception: %s - Data received %s',
context['request'].build_absolute_uri(),
exception_str,
context['request'].data)
return response
示例3: post
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def post(self, request, *args, **kwargs):
weixin_config = request.data
weixin = WorkWeiXin(corp_id=weixin_config['WEIXIN_CORP_ID'], corp_secret=weixin_config['WEIXIN_CORP_SECRET'],
agent_id=weixin_config['WEIXIN_AGENT_ID'])
result = weixin.get_token()
if result.success:
redis_cli = redis.StrictRedis(host=kubeoperator.settings.REDIS_HOST,
port=kubeoperator.settings.REDIS_PORT)
redis_cli.set('WORK_WEIXIN_TOKEN', result.data['access_token'], result.data['expires_in'])
if weixin_config.get('WEIXIN_TEST_USER') is not None and weixin_config['WEIXIN_TEST_USER'] != '':
res = weixin.send_markdown_msg(receivers=weixin_config['WEIXIN_TEST_USER'], content={'content': '测试消息'},
token=result.data['access_token'])
if res.success:
return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK)
else:
return Response(data={'msg': '校验失败!' + json.dumps(res.data)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK)
else:
return Response(data={'msg': '校验失败!' + json.dumps(result.data)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
示例4: post
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def post(self, request, token):
serializer = UpdateSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
try:
bot = Bot.objects.get(token=token)
bot.handle(Update.de_json(request.data, bot._bot))
except Bot.DoesNotExist:
logger.warning("Token %s not associated to a bot" % token)
return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)
except:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
logger.error("Error processing %s for token %s" % (request.data, token))
return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
return Response(serializer.data, status=status.HTTP_200_OK)
logger.error("Validation error: %s from message %s" % (serializer.errors, request.data))
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例5: handle_upload
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def handle_upload(self, request, upload_id, file_id=None):
# Since the upload_id is being provided here as a paramter, we check
# it is valid. This should be done by the DB but for some DBs, e.g.
# SQLite field length validation isn't handled. The same check is
# done for file_id in the case of POST requests.
if not self._upload_id_valid(upload_id):
return Response('Invalid ID for handling upload.',
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
if request.method == 'PATCH':
return self._handle_chunk_upload(request, upload_id)
elif request.method == 'HEAD':
return self._handle_chunk_restart(request, upload_id)
elif request.method == 'POST':
if not self._file_id_valid(file_id):
return Response('Invalid ID for handling upload.',
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return self._handle_new_chunk_upload(request, upload_id, file_id)
示例6: post
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def post(self, request):
data = request.data['checkout']
total = len(data) * 5
queryset = CharityModel.objects.all()
my_profile = get_object_or_404(MyProfile, owner=request.user)
if my_profile.my_wallet < total:
return Response({"error": "Insufficient leancoins to proceed with the transaction."},
status=status.HTTP_400_BAD_REQUEST)
try:
for element in data:
charity = get_object_or_404(queryset, pk=int(element))
DonationModel.objects.create(donor=request.user, charity=charity)
my_profile.my_wallet -= total
my_profile.save()
except Http404:
return Response({"error": "We couldn't proceed with transaction at this time. Try again later"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response({"message": "You have successfully paid"}, status=status.HTTP_201_CREATED)
示例7: _save_and_publish
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def _save_and_publish(self, data, course_id=None):
"""Create or update a Course and associated products, then publish the result."""
if course_id is not None:
data['id'] = course_id
serializer = self.get_serializer(data=data)
is_valid = serializer.is_valid(raise_exception=True)
if not is_valid:
return None
created, failure, message = serializer.save()
if failure:
return Response({'error': message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
content = serializer.data
content['message'] = message if message else None
return Response(content, status=status.HTTP_201_CREATED if created else status.HTTP_200_OK)
示例8: update
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def update(self, request, *args, **kwargs):
APPROVE = 'approve'
DENY = 'deny'
APPROVE_PAYMENT_ONLY = 'approve_payment_only'
action = request.data.get('action', '').lower()
if action not in (APPROVE, DENY, APPROVE_PAYMENT_ONLY):
raise ParseError('The action [{}] is not valid.'.format(action))
with transaction.atomic():
refund = self.get_object()
result = False
if action in (APPROVE, APPROVE_PAYMENT_ONLY):
revoke_fulfillment = action == APPROVE
result = refund.approve(revoke_fulfillment=revoke_fulfillment)
elif action == DENY:
result = refund.deny()
http_status = status.HTTP_200_OK if result else status.HTTP_500_INTERNAL_SERVER_ERROR
serializer = self.get_serializer(refund)
return Response(serializer.data, status=http_status)
示例9: retrieve
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def retrieve(self, request, **kwargs):
endpoint_request_url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()
try:
catalog = get_enterprise_catalog(
site=request.site,
enterprise_catalog=kwargs.get('enterprise_catalog_uuid'),
limit=request.GET.get('limit', DEFAULT_CATALOG_PAGE_SIZE),
page=request.GET.get('page', '1'),
endpoint_request_url=endpoint_request_url
)
except (ReqConnectionError, SlumberHttpBaseException, Timeout) as exc:
logger.exception(
'Unable to retrieve catalog for enterprise customer! customer: %s, Exception: %s',
kwargs.get('enterprise_catalog_uuid'),
exc
)
return Response(
{'error': 'Unable to retrieve enterprise catalog. Exception: {}'.format(six.text_type(exc))},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
return Response(catalog)
示例10: fulfill
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def fulfill(self, request, number=None): # pylint: disable=unused-argument
""" Fulfill order """
order = self.get_object()
if not order.is_fulfillable:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
# Get email_opt_in from the query parameters if it exists, defaulting to false
email_opt_in = request.query_params.get('email_opt_in', False) == 'True'
logger.info('Attempting fulfillment of order [%s]...', order.number)
with transaction.atomic():
post_checkout.send(
sender=post_checkout,
order=order,
request=request,
email_opt_in=email_opt_in,
)
if order.is_fulfillable:
logger.warning('Fulfillment of order [%s] failed!', order.number)
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
serializer = self.get_serializer(order)
return Response(serializer.data)
示例11: publish
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def publish(self, request, pk=None): # pylint: disable=unused-argument
""" Publish the course to LMS. """
course = self.get_object()
published = False
msg = 'Course [{course_id}] was not published to LMS ' \
'because the switch [publish_course_modes_to_lms] is disabled.'
if waffle.switch_is_active('publish_course_modes_to_lms'):
published = course.publish_to_lms()
if published:
msg = 'Course [{course_id}] was successfully published to LMS.'
else:
msg = 'An error occurred while publishing [{course_id}] to LMS.'
return Response({'status': msg.format(course_id=course.id)},
status=status.HTTP_200_OK if published else status.HTTP_500_INTERNAL_SERVER_ERROR)
示例12: test_view_response_improperly_configured
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def test_view_response_improperly_configured(self):
"""
Test that the SearchResultMailView will raise ImproperlyConfigured if mailgun returns 401, which
results in returning 500 since micromasters.utils.custom_exception_handler catches ImproperlyConfigured
"""
with patch(
'mail.views.get_all_query_matching_emails', autospec=True, return_value=self.email_results
), patch(
'mail.views.MailgunClient'
) as mock_mailgun_client, patch(
'mail.views.get_mail_vars', autospec=True, return_value=self.email_vars,
) as mock_get_mail_vars:
mock_mailgun_client.send_batch.side_effect = ImproperlyConfigured
resp = self.client.post(self.search_result_mail_url, data=self.request_data, format='json')
assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
mock_get_mail_vars.assert_called_once_with(self.email_results)
示例13: test_generate_mailgun_response_json_with_failed_json_call
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def test_generate_mailgun_response_json_with_failed_json_call(self):
"""
Tests that generate_mailgun_response_json() returns without erroring if Response.json() call fails for
non 401 status code
"""
# Response.json() error
response = Mock(
spec=Response,
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
json=lambda: (_ for _ in []).throw(ValueError), # To get .json() to throw ValueError
reason="reason"
)
self.assertDictEqual(
generate_mailgun_response_json(response),
{"message": response.reason}
)
示例14: custom_exception_handler
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def custom_exception_handler(exc, context):
"""
Custom exception handler for rest api views
"""
# Call REST framework's default exception handler first,
# to get the standard error response.
log.exception("An exception was intercepted by custom_exception_handler")
response = exception_handler(exc, context)
# if it is handled, just return the response
if response is not None:
return response
# Otherwise format the exception only in specific cases
if isinstance(exc, ImproperlyConfigured):
# send the exception to Sentry anyway
client.capture_exception()
formatted_exception_string = "{0}: {1}".format(type(exc).__name__, str(exc))
return Response(
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
data=[formatted_exception_string]
)
return None
示例15: test_500_error_context_logged_out
# 需要导入模块: from rest_framework import status [as 别名]
# 或者: from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR [as 别名]
def test_500_error_context_logged_out(self):
"""
Assert context values for 500 error page when logged out
"""
# case with specific page
with patch('ui.templatetags.render_bundle._get_bundle') as get_bundle:
response = self.client.get('/500/')
assert response.context['authenticated'] is False
assert response.context['name'] == ""
assert response.context['is_public'] is True
assert response.context['has_zendesk_widget'] is True
self.assertContains(response, 'Share this page', status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
bundles = [bundle[0][1] for bundle in get_bundle.call_args_list]
assert set(bundles) == {
'public',
'sentry_client',
'style',
'style_public',
'zendesk_widget',
}