def page_not_found(request, exception, template_name='404.html'):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
exception
The message from the exception which triggered the 404 (if one was
supplied), or the exception class name
"""
exception_repr = exception.__class__.__name__
# Try to get an "interesting" exception message, if any (and not the ugly
# Resolver404 dictionary)
try:
message = exception.args[0]
except (AttributeError, IndexError):
pass
else:
if isinstance(message, six.text_type):
exception_repr = message
context = {
'request_path': request.path,
'exception': exception_repr,
}
try:
template = loader.get_template(template_name)
body = template.render(context, request)
content_type = None # Django will use DEFAULT_CONTENT_TYPE
except TemplateDoesNotExist:
template = Engine().from_string(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(Context(context))
content_type = 'text/html'
return http.HttpResponseNotFound(body, content_type=content_type)
python类HttpResponseNotFound()的实例源码
def site_screenshot(request: HttpRequest, site_id: int) -> HttpResponse:
"""View a site and its most recent scan result (if any)."""
site = get_object_or_404(Site, pk=site_id)
screenshot = site.get_screenshot()
if not screenshot:
return HttpResponseNotFound(_('screenshot does not exist'))
return HttpResponse(screenshot, content_type='image/png')
def get(self, request, *args, **kwargs):
action_name = self.kwargs.get('action_name')
if action_name == "contact":
self.template_name = 'package/contact.html'
elif action_name == "history":
self.template_name = 'package/history.html'
elif action_name is None:
self.template_name = 'package/package.html'
else:
return HttpResponseNotFound()
return super(PackageView, self).get(request, *args, **kwargs)
def package_file_fetch(request, package_id):
pref = preferences.Setting
pkg = Version.objects.get(id=int(package_id))
if not pkg:
return HttpResponseNotFound()
file_path = os.path.join(settings.MEDIA_ROOT, pkg.storage.name)
if not os.path.exists(file_path):
return HttpResponseNotFound()
if pref.download_cydia_only:
if 'HTTP_X_UNIQUE_ID' not in request.META:
return HttpResponseBadRequest()
request_path = pkg.storage.name
request_url = pkg.get_external_storage_link()
pkg.download_times = pkg.download_times + 1
pkg.save()
if pref.redirect_resources == 1:
# Redirect URLs
return redirect(request_url)
elif pref.redirect_resources == 2:
# Redirect to WEB server
response = HttpResponse()
if pref.web_server == 0:
response['X-Accel-Redirect'] = request_url
elif pref.web_server == 1:
# You may set Send File Path to settings.MEDIA_ROOT
response['X-sendfile'] = request_path
elif pref.web_server == 2:
pass
else:
# Return FileResponse By Reading Static File
response = serve(
request,
path=request_path,
document_root=settings.MEDIA_ROOT,
)
response['Content-Type'] = 'application/octet-stream'
response['Content-Transfer-Encoding'] = "binary"
response['Cache-Control'] = "public, must-revalidate, max-age=0"
response['Content-Disposition'] = "attachment; filename=\"" + urllib.quote_plus(pkg.base_filename()) + "\""
return response
def notfound(request):
return HttpResponseNotFound('not found!!!')
def order_is_done(request):
oid = request.GET.get('id', False)
if not oid:
return HttpResponseNotFound(NOTFOUNDMESSAGE)
try:
obj = Order.objects.get(pk=int(oid), user=request.user)
obj.is_done = True
obj.save()
return HttpResponseRedirect(reverse('ucenterindex'))
except:
return HttpResponseNotFound(NOTFOUNDMESSAGE)
def business_order_is_done(request):
oid = request.GET.get('id', False)
if not oid:
return HttpResponseNotFound(NOTFOUNDMESSAGE)
try:
obj = Order.objects.get(pk=int(oid), food__business__user=request.user)
obj.is_done = True
obj.save()
return HttpResponseRedirect(reverse('businessucenterindex') + '?s=now')
except:
return HttpResponseNotFound(NOTFOUNDMESSAGE)
def changeopen(request):
if request.user.usertype:
return HttpResponseForbidden()
else:
try:
b = request.user.business
b.is_open = not b.is_open
b.save()
return HttpResponseRedirect(reverse('businessucenterindex'))
except:
return HttpResponseNotFound(NOTFOUNDMESSAGE)
def post(self, request):
if not request.user.usertype:
return JsonResponse({'status': 2})
if not request.user.can_order:
return JsonResponse({'status': -1})
if request.user.get_no_done_order_list():
return JsonResponse({'status': -2})
confirm = request.POST.get('confirm', False)
time = request.POST.get('time', False)
remarkstr = request.POST.get('remarkstr', '')
if confirm:
try:
orderdic = request.session['order']
except:
return HttpResponseNotFound("?????")
try:
for fpk in orderdic.keys():
if fpk == 'business':
b = Business.objects.get(pk=orderdic['business'])
if not b.is_open:
return JsonResponse({'status': 0})
else:
f = Food.objects.get(pk=fpk)
Order.objects.create(user=request.user, food=f, date_pickup=time, remark=remarkstr)
except Exception as e:
print(e)
return JsonResponse({'status': 0})
return JsonResponse({'status': 1})
else:
return JsonResponse({'status': 0})
def comment(request, opk):
try:
order = request.user.myorder.get(pk=opk)
business = order.food.business
except:
return HttpResponseNotFound()
if not order.is_done:
return HttpResponseNotFound()
if request.method == 'GET':
return render(request, 'operation/comment.html', {
'order': order
})
elif request.method == 'POST':
trank = int(request.POST.get('trank', False))
prank = int(request.POST.get('prank', False))
textcomment = request.POST.get('textcomment', False)
try:
order.trank, order.prank = trank, prank
average = (trank + prank) / 2
order.is_comment = True
order.save()
if textcomment:
BusinessTextComment.objects.create(business=order.food.business, comment=textcomment)
num_order = Order.objects.filter(is_comment=True).count()
business.total_rank = business.total_rank + average
business.rank = round(business.total_rank / num_order)
business.save()
return JsonResponse({'status': 1})
except Exception as e:
print(e)
return JsonResponse({'status': 0})
def version(request):
"""
Returns the contents of version.json or a 404.
"""
version_json = import_string(version_callback)(settings.BASE_DIR)
if version_json is None:
return HttpResponseNotFound('version.json not found')
else:
return JsonResponse(version_json)
def log_kill(request):
""" ??connect?? """
pid = request.GET.get('id', '')
log = Log.objects.filter(pid=pid)
if log:
log = log[0]
try:
os.kill(int(pid), 9)
except OSError:
pass
Log.objects.filter(pid=pid).update(is_finished=1, end_time=datetime.datetime.now())
return render_to_response('jlog/log_offline.html', locals(), context_instance=RequestContext(request))
else:
return HttpResponseNotFound(u'?????!')
def upload_csv(request, form_class):
"""
Upload csv file to server and validate it.
:param form_class: - form class to instantiate (taken from urls.py)
:rtype: HttpResponse
"""
csv_file = request.FILES.get('0')
if csv_file:
# Apply custom validation
new_csv_file = None
try:
new_csv_file = form_class.validate_csv_file(csv_file)
except Exception:
pass
if not new_csv_file:
return HttpResponseNotFound(simplejson.dumps({'response': _('File is not valid')}))
else:
response = {'response': _('File is valid'), 'lines': new_csv_file.line_count,
'names': new_csv_file.names}
if new_csv_file.warning:
# add warning
response['warning'] = new_csv_file.warning
response['response'] = _('File is partially valid')
request.session[form_class.CSV_FILE_NAME] = new_csv_file
return HttpResponse(simplejson.dumps(response))
raise Http404
def get_http_error(exception):
"""
Returns proper http failure status code according to the provided exception.
"""
if 'Not a git repository' in exception.args[0]:
return HttpResponseNotFound()
def wfmodule_render(request, pk, format=None):
if request.method == 'GET':
try:
wf_module = WfModule.objects.get(pk=pk)
except WfModule.DoesNotExist:
return HttpResponseNotFound()
if not wf_module.workflow.user_authorized_read(request.user):
return HttpResponseForbidden()
return table_result(request, wf_module)
# /input is just /render on the previous wfmodule
def forgot_passwd(request):
"""Password email page / post endpoint."""
if request.method == 'POST' and request.POST.get('email'):
try:
user = User.objects.get(email=request.POST['email'])
except (User.DoesNotExist, ValueError):
return HttpResponseNotFound("There isn't a user with that email address.")
try:
user.password_reset_email(request)
except:
return HttpResponseBadRequest("There was an error submitting that.")
return HttpResponse("Success! Check your emails, it should have been sent from \"{0}\".".format(settings.DEFAULT_FROM_EMAIL))
if request.GET.get('token'):
user = User.get_from_passwd(request.GET['token'])
if not user:
raise Http404()
if request.method == 'POST':
if not request.POST['password'] == request.POST['password_again']:
return HttpResponseBadRequest("Your passwords don't match.")
user.set_password(request.POST['password'])
user.save()
return HttpResponse("Success! Now you can log in with your new password!")
return render(request, 'closedverse_main/forgot_reset.html', {
'title': 'Reset password for ' + user.username,
#'classes': ['no-login-btn'],
})
return render(request, 'closedverse_main/forgot_page.html', {
'title': 'Reset password',
#'classes': ['no-login-btn'],
})
def post_create(request, community):
if request.method == 'POST' and request.is_ajax():
# Wake
request.user.wake(request.META['REMOTE_ADDR'])
# Required
if not (request.POST.get('community')):
return HttpResponseBadRequest()
try:
community = Community.objects.get(id=community, unique_id=request.POST['community'])
except (Community.DoesNotExist, ValueError):
return HttpResponseNotFound()
# Method of Community
new_post = community.create_post(request)
if not new_post:
return HttpResponseBadRequest()
if isinstance(new_post, int):
# If post limit
if new_post == 8:
# then do meme
return json_response("You have already exceeded the number of posts that you can contribute in a single day. Please try again tomorrow.", 1215919)
return json_response({
1: "Your post is too long ("+str(len(request.POST['body']))+" characters, 2200 max).",
2: "The image you've uploaded is invalid.",
3: "You're making posts too fast, wait a few seconds and try again.",
4: "Apparently, you're not allowed to post here.",
5: "Uh-oh, that URL wasn't valid..",
6: "Not allowed.",
7: "Please don't spam.",
}.get(new_post))
# Render correctly whether we're posting to Activity Feed
if community.is_activity():
return render(request, 'closedverse_main/elements/community_post.html', {
'post': new_post,
'with_community_container': True,
'type': 2,
})
else:
return render(request, 'closedverse_main/elements/community_post.html', { 'post': new_post })
else:
raise Http404()
def notification_delete(request, notification):
if not request.method == 'POST':
raise Http404()
try:
notification = Notification.objects.get(to=request.user, unique_id=notification)
except Notification.DoesNotExist:
return HttpResponseNotFound()
remove = notification.delete()
return HttpResponse()
#@silk_profile(name='Notifications view')
def test_get_node(self):
"""
Fuzzy test
Test whether indexing yields the correct response type
"""
node = views.get_node(self.rf.get('/node?index=0'))
self.assertTrue(isinstance(node, HttpResponse))
self.assertFalse(isinstance(node, HttpResponseNotFound))
node = views.get_node(self.rf.get('/node?index=-5'))
self.assertTrue(isinstance(node, HttpResponseNotFound))
def rate_route(request):
"""
Adds the rating to all edges in a route, and saves it both in the structure and in the database.
Query args:
rid -- the id for the rated route
rating -- a float between 0 and 5
"""
try:
tag = request.POST.get('visited_path')
new_rating = float(request.POST.get('rating'))
path = from_string(GRAPH, tag)
edgecoords = [(s, e) for s, e in zip(path, path[1:])]
def update_rating(edge):
for edge in GRAPH.get_edges():
for s, e in edgecoords:
if s == edge.id and e == edge.to:
edge._rating = (edge._rating + new_rating) / 2
update_edge_in_db(edge)
return edge
GRAPH.map_graph(lambda _: _, update_rating)
return HttpResponse('')
except:
return HttpResponseNotFound("Something went wrong while rating your route.")