本文整理汇总了Python中django.http.Http404方法的典型用法代码示例。如果您正苦于以下问题:Python http.Http404方法的具体用法?Python http.Http404怎么用?Python http.Http404使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http
的用法示例。
在下文中一共展示了http.Http404方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: custom_exception_handler
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def custom_exception_handler(exc, context):
# give more context on the error since DRF masks it as Not Found
if isinstance(exc, Http404):
set_rollback()
return Response(str(exc), status=status.HTTP_404_NOT_FOUND)
# Call REST framework's default exception handler after specific 404 handling,
# to get the standard error response.
response = exception_handler(exc, context)
# No response means DRF couldn't handle it
# Output a generic 500 in a JSON format
if response is None:
logging.exception('Uncaught Exception', exc_info=exc)
set_rollback()
return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# log a few different types of exception instead of using APIException
if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
logging.exception(exc.__cause__, exc_info=exc)
return response
示例2: process_exception
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def process_exception(self, request, exception):
if not self._settings.log_exceptions:
return None
if isinstance(exception, Http404):
return None
_, _, tb = sys.exc_info() # pylint: disable=invalid-name
if tb is None or exception is None:
# No actual traceback or exception info, don't bother logging.
return None
client = common.get_telemetry_client_with_processor(
self._client.context.instrumentation_key, self._client.channel
)
if hasattr(request, "appinsights"):
client.context.operation.parent_id = request.appinsights.request.id
client.track_exception(type(exception), exception, tb)
return None
示例3: get_relations
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def get_relations(self):
paginator = self.get_paginator()
try:
page = paginator.page(int(self.request.GET.get('page', 1)))
except EmptyPage:
raise Http404()
objects = page.object_list
relations = {
self.relation: self.get_resources(page)
}
relations['first'] = self.__class__()
if page.has_next():
relations['next'] = self.__class__(page.next_page_number())
if page.has_previous():
relations['prev'] = self.__class__(page.previous_page_number())
if page.has_other_pages():
relations['last'] = self.__class__(paginator.num_pages)
return relations
示例4: process_reset_password_data
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def process_reset_password_data(input_data, serializer_context=None):
if serializer_context is None:
serializer_context = {}
if not registration_settings.RESET_PASSWORD_VERIFICATION_ENABLED:
raise Http404()
serializer = ResetPasswordSerializer(
data=input_data,
context=serializer_context,
)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data.copy()
password = data.pop('password')
data.pop('password_confirm', None)
signer = ResetPasswordSigner(data)
verify_signer_or_bad_request(signer)
user = get_user_by_verification_id(data['user_id'], require_verified=False)
user.set_password(password)
user.save()
示例5: process_verify_registration_data
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def process_verify_registration_data(input_data, serializer_context=None):
if serializer_context is None:
serializer_context = {}
if not registration_settings.REGISTER_VERIFICATION_ENABLED:
raise Http404()
serializer = VerifyRegistrationSerializer(
data=input_data,
context=serializer_context,
)
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
signer = RegisterSigner(data)
verify_signer_or_bad_request(signer)
verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD')
user = get_user_by_verification_id(data['user_id'], require_verified=False)
setattr(user, verification_flag_field, True)
user.save()
return user
示例6: get_user_by_lookup_dict
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def get_user_by_lookup_dict(
lookup_dict, default=_RAISE_EXCEPTION, require_verified=True):
verification_enabled = registration_settings.REGISTER_VERIFICATION_ENABLED
verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD')
user_class = get_user_model()
kwargs = {}
kwargs.update(lookup_dict)
if require_verified and verification_enabled and verification_flag_field:
kwargs[verification_flag_field] = True
try:
user = get_object_or_404(user_class.objects.all(), **kwargs)
except Http404:
if default is _RAISE_EXCEPTION:
raise UserNotFound()
return default
else:
return user
示例7: index
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def index(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
role = request.member.role
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
if role in ['INST', 'TA']:
quiz = Quiz.objects.filter(activity=activity).first() # will be None if no quiz created for this activity
if not quiz:
# no quiz created? Only option is to create.
return redirect('offering:quiz:edit', course_slug=course_slug, activity_slug=activity_slug)
return _index_instructor(request, offering, activity, quiz)
elif role == 'STUD':
quiz = get_object_or_404(Quiz, activity=activity) # will 404 if no quiz created for this activity
return _index_student(request, offering, activity, quiz)
else:
raise Http404()
示例8: submitted_file
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id)
real_secret = answer.answer['data'].get('secret', '?')
if real_secret != '?' and secret == real_secret:
return _return_submitted_file(answer.answer['data'], answer.file.open('rb'))
else:
# It's not the current submission, but an instructor looking at history might be trying to find an old one...
submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member)
for qs in submissions:
for answer_config in qs.config['answers']:
version_id, answer_id, a = answer_config
if not isinstance(a['data'], dict):
continue
real_secret = a['data'].get('secret', '?')
if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret:
# aha! Temporarily replace answer.file with the old version (without saving) so we can return it
answer.file = a['filepath']
return _return_submitted_file(a['data'], answer.file.open('rb'))
raise Http404()
示例9: file_field_download_unauth
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def file_field_download_unauth(request, form_slug, formsubmit_slug, file_id, action, secret):
"""
Version of file_field_download that doesn't require authentication, but does require knowing the "secret" URL
component. Used to provide URLs in the CSV export.
"""
file_sub = get_object_or_404(FieldSubmissionFile,
field_submission__sheet_submission__form_submission__slug=formsubmit_slug,
field_submission__sheet_submission__form_submission__form__slug=form_slug,
id=file_id)
form_submission = file_sub.field_submission.sheet_submission.form_submission
field_sub = file_sub.field_submission
if ('secret' not in field_sub.data) \
or (not field_sub.data['secret']) \
or (len(field_sub.data['secret']) != FILE_SECRET_LENGTH) \
or (field_sub.data['secret'] != secret):
raise Http404
return _file_field_download(form_submission, file_sub, action)
示例10: reopen_submission
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def reopen_submission(request, form_slug, formsubmit_slug):
# The wording here is tricky. The _formsubmission_find_and_authz method only returns "is_advisor" if you are
# *only* an advisor, but not in the form group that owns the form. If you are in the form group, is_advisor is
# false, and form_submission will be the instance we want to work on.
form_submission, is_advisor = _formsubmission_find_and_authz(request, form_slug, formsubmit_slug)
if not form_submission:
raise Http404
# Therefore, if you're not a supervisor and you had a form_submission returned, you're in the form group and
# can re-open it.
can_reopen = not is_advisor and form_submission.status == 'DONE'
if can_reopen and request.method == 'POST':
form_submission.reopen(requester=request.user.username)
messages.success(request, "Form re-opened")
l = LogEntry(userid=request.user.username,
description=("Re-opened Form Submission %s") % form_submission,
related_object=form_submission)
l.save()
else:
messages.error(request, "The form could no be re-opened. Perhaps it was already re-opened, or you do not "
"have permission to perform this action.")
return HttpResponseRedirect(reverse('onlineforms:view_submission', kwargs={'form_slug': form_slug,
'formsubmit_slug': formsubmit_slug}))
示例11: change_grade_status
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def change_grade_status(request, course_slug, activity_slug, userid):
"""
Grade status form. Calls numeric/letter view as appropriate.
"""
course = get_object_or_404(CourseOffering, slug=course_slug)
acts = all_activities_filter(course, slug=activity_slug)
if len(acts) != 1:
raise Http404('No such Activity.')
activity = acts[0]
if isinstance(activity, NumericActivity):
return _change_grade_status_numeric(request, course, activity, userid)
elif isinstance(activity, LetterActivity):
return _change_grade_status_letter(request, course, activity, userid)
else:
raise Http404('Unknown activity type.')
示例12: mark_all_groups
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def mark_all_groups(request, course_slug, activity_slug):
"""
Mark the whole class (by group). Calls numeric/letter view as appropriate.
"""
course = get_object_or_404(CourseOffering, slug = course_slug)
acts = all_activities_filter(course, slug=activity_slug)
if len(acts) != 1:
raise Http404('No such Activity.')
activity = acts[0]
if isinstance(activity, NumericActivity):
return _mark_all_groups_numeric(request, course, activity)
elif isinstance(activity, LetterActivity):
return _mark_all_groups_letter(request, course, activity)
else:
raise Http404('Unknown activity type.')
示例13: mark_all_students
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def mark_all_students(request, course_slug, activity_slug):
"""
Mark the whole class (by student). Calls numeric/letter view as appropriate.
"""
course = get_object_or_404(CourseOffering, slug = course_slug)
acts = all_activities_filter(course, slug=activity_slug)
if len(acts) != 1:
raise Http404('No such Activity.')
activity = acts[0]
if isinstance(activity, NumericActivity):
return _mark_all_students_numeric(request, course, activity)
elif isinstance(activity, LetterActivity):
return _mark_all_students_letter(request, course, activity)
else:
raise Http404('Unknown activity type.')
示例14: export_marks
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def export_marks(request, course_slug, activity_slug):
"""
Export JSON marking data
"""
course = get_object_or_404(CourseOffering, slug=course_slug)
acts = all_activities_filter(course, slug=activity_slug)
if len(acts) != 1:
raise Http404('No such Activity.')
activity = acts[0]
data = _mark_export_data(activity)
response = HttpResponse(content_type='application/json')
response['Content-Disposition'] = 'inline; filename="%s-%s.json"' % (course.slug, activity.slug)
json.dump({'marks': data}, response, cls=_DecimalEncoder, indent=1)
return response
示例15: init_request
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import Http404 [as 别名]
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)