本文整理汇总了Python中django.http.HttpResponseNotFound方法的典型用法代码示例。如果您正苦于以下问题:Python http.HttpResponseNotFound方法的具体用法?Python http.HttpResponseNotFound怎么用?Python http.HttpResponseNotFound使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http
的用法示例。
在下文中一共展示了http.HttpResponseNotFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: feature_popup_content
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def feature_popup_content(request):
url = request.POST.get("url", None)
if url is not None:
host = "{uri.hostname}".format(uri=urlparse(url))
try:
if host in settings.ALLOWED_POPUP_HOSTS:
if url is not None:
f = urllib.request.urlopen(url)
return HttpResponse(f.read())
else:
raise Exception()
except:
return HttpResponseNotFound()
else:
return HttpResponseNotFound()
示例2: post
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def post(self, request, cardid=None):
data = JSONDeserializer().deserialize(request.body)
if self.action == "update_card":
if data:
card = Card(data)
card.save()
return JSONResponse(card)
if self.action == "reorder_cards":
if "cards" in data and len(data["cards"]) > 0:
with transaction.atomic():
for card_data in data["cards"]:
card = models.CardModel.objects.get(pk=card_data["id"])
card.sortorder = card_data["sortorder"]
card.save()
return JSONResponse(data["cards"])
return HttpResponseNotFound()
示例3: delete
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def delete(self, request):
mobile_survey_id = None
try:
mobile_survey_id = JSONDeserializer().deserialize(request.body)["id"]
except Exception as e:
logger.exception(e)
try:
connection_error = False
with transaction.atomic():
if mobile_survey_id is not None:
ret = MobileSurvey.objects.get(pk=mobile_survey_id)
ret.delete()
return JSONResponse({"success": True})
except Exception as e:
if connection_error is False:
error_title = _("Unable to delete collector project")
if "strerror" in e and e.strerror == "Connection refused" or "Connection refused" in e:
error_message = _("Unable to connect to CouchDB")
else:
error_message = e.message
connection_error = JSONResponse({"success": False, "message": error_message, "title": error_title}, status=500)
return connection_error
return HttpResponseNotFound()
示例4: get
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def get(self, request, resourceid=None):
if Resource.objects.filter(pk=resourceid).exclude(pk=settings.SYSTEM_SETTINGS_RESOURCE_ID).exists():
try:
resource = Resource.objects.get(pk=resourceid)
se = SearchEngineFactory().create()
document = se.search(index="resources", id=resourceid)
return JSONResponse(
{
"graphid": document["_source"]["graph_id"],
"graph_name": resource.graph.name,
"displaydescription": document["_source"]["displaydescription"],
"map_popup": document["_source"]["map_popup"],
"displayname": document["_source"]["displayname"],
"geometries": document["_source"]["geometries"],
"permissions": document["_source"]["permissions"],
"userid": request.user.id,
}
)
except Exception as e:
logger.exception(_("Failed to fetch resource instance descriptors"))
return HttpResponseNotFound()
示例5: django_test_runner
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def django_test_runner(request):
unknown_args = [arg for (arg, v) in request.REQUEST.items()
if arg not in ("format", "package", "name")]
if len(unknown_args) > 0:
errors = []
for arg in unknown_args:
errors.append(_log_error("The request parameter '%s' is not valid." % arg))
from django.http import HttpResponseNotFound
return HttpResponseNotFound(" ".join(errors))
format = request.REQUEST.get("format", "html")
package_name = request.REQUEST.get("package")
test_name = request.REQUEST.get("name")
if format == "html":
return _render_html(package_name, test_name)
elif format == "plain":
return _render_plain(package_name, test_name)
else:
error = _log_error("The format '%s' is not valid." % cgi.escape(format))
from django.http import HttpResponseServerError
return HttpResponseServerError(error)
示例6: ProxyAuth
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def ProxyAuth(func):
@wraps(func)
def wrapped_func(request, *args, **kw):
# if not request.META.get("HTTP_WEICHAT_USER"):
# return HttpResponseForbidden()
# # return HttpResponse(status=403)
# # return HttpResponseNotFound('<h1>Page not found</h1>')
# pass
# print("\33[36mURI %s\33[0m"%request.build_absolute_uri())
# print(dict((regex.sub('', header), value) for (header, value)
# in request.META.items() if header.startswith('HTTP_')))
# print("\33[34mProxy: is_ajax:%s,WeiChat:[%s],AddR:[%s], Custome:[%s], X_F_F:%s, UA:%.10s\33[0m" % (
# request.is_ajax(),
# request.META.get("HTTP_WEICHAT_USER", "None"),
# request.META.get("REMOTE_ADDR", "None"),
# request.META.get("HTTP_CUSTOMPROXY", "None"),
# request.META.get("HTTP_X_FORWARDED_FOR", "None"),
# request.META.get("HTTP_USER_AGENT", "None"),
# ))
print('is_ajax: %s' % request.is_ajax())
return func(request, *args, **kw)
return wrapped_func
示例7: page_not_found
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def page_not_found(request, 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/')
"""
context = {'request_path': request.path}
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)
示例8: get_media_file_response
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def get_media_file_response(metadata):
if metadata.data_file:
file_path = metadata.data_file.name
filename, extension = os.path.splitext(file_path.split('/')[-1])
extension = extension.strip('.')
dfs = get_storage_class()()
if dfs.exists(file_path):
response = response_with_mimetype_and_name(
metadata.data_file_type,
filename, extension=extension, show_date=False,
file_path=file_path, full_mime=True)
return response
else:
return HttpResponseNotFound()
else:
return HttpResponseRedirect(metadata.data_value)
示例9: check_user
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def check_user(request):
ya_login = request.GET.get('ya_login')
if not ya_login:
return HttpResponseBadRequest()
try:
profile = UserProfile.objects.select_related('user').get(ya_passport_login=ya_login)
except UserProfile.DoesNotExist:
return HttpResponseNotFound('No profile found')
user = profile.user
return HttpResponse(json.dumps({
'id': user.id,
'ya_passport_login': ya_login,
'active': user.is_active,
'is_staff': user.is_staff or user.is_superuser,
'is_teacher': user.course_teachers_set.exists(),
}), content_type="application/json")
示例10: integration_doc
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def integration_doc(request: HttpRequest, integration_name: str=REQ()) -> HttpResponse:
if not request.is_ajax():
return HttpResponseNotFound()
try:
integration = INTEGRATIONS[integration_name]
except KeyError:
return HttpResponseNotFound()
context: Dict[str, Any] = {}
add_api_uri_context(context, request)
context['integration_name'] = integration.name
context['integration_display_name'] = integration.display_name
context['recommended_stream_name'] = integration.stream_name
if isinstance(integration, WebhookIntegration):
context['integration_url'] = integration.url[3:]
if isinstance(integration, HubotIntegration):
context['hubot_docs_url'] = integration.hubot_docs_url
doc_html_str = render_markdown_path(integration.doc, context)
return HttpResponse(doc_html_str)
示例11: user_subscribe_feed
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def user_subscribe_feed(request):
"""
已登录用户订阅源
"""
feed = request.POST.get('feed', '').strip()[:32]
user = get_login_user(request)
if user and feed:
try:
Site.objects.get(name=feed)
add_user_sub_feeds(user.oauth_id, [feed, ])
logger.warning(f"登陆用户订阅动作:`{user.oauth_name}`{feed}")
return JsonResponse({"name": feed})
except:
logger.warning(f'用户订阅出现异常:`{feed}`{user.oauth_id}')
return HttpResponseNotFound("Param error")
示例12: get_article_detail
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def get_article_detail(request):
"""
获取文章详情;已登录用户记录已读
"""
uindex = request.POST.get('id')
user = get_login_user(request)
mobile = request.POST.get('mobile', False)
try:
article = Article.objects.get(uindex=uindex, status='active')
except:
logger.info(f"获取文章详情请求处理异常:`{uindex}")
return HttpResponseNotFound("Param error")
if user:
set_user_read_article(user.oauth_id, uindex)
context = dict()
context['article'] = article
context['user'] = user
if mobile:
return render(request, 'mobile/article.html', context=context)
else:
return render(request, 'article/index.html', context=context)
示例13: delete
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def delete(self, request, pk):
try:
odlc = find_odlc(request, int(pk))
except Odlc.DoesNotExist:
return HttpResponseNotFound('Odlc %s not found' % pk)
except ValueError as e:
return HttpResponseForbidden(str(e))
# Remember the thumbnail path so we can delete it from disk.
thumbnail = odlc.thumbnail.path if odlc.thumbnail else None
odlc.delete()
if thumbnail:
try:
os.remove(thumbnail)
except OSError as e:
logger.warning("Unable to delete thumbnail: %s", e)
return HttpResponse("Odlc deleted.")
示例14: put
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def put(self, request, pk):
"""Updates the review status of a odlc."""
review_proto = interop_admin_api_pb2.OdlcReview()
try:
json_format.Parse(request.body, review_proto)
except Exception:
return HttpResponseBadRequest('Failed to parse review proto.')
try:
odlc = find_odlc(request, int(pk))
except Odlc.DoesNotExist:
return HttpResponseNotFound('Odlc %s not found' % pk)
except ValueError as e:
return HttpResponseForbidden(str(e))
update_odlc_from_review_proto(odlc, review_proto)
odlc.save()
return HttpResponse(json_format.MessageToJson(
odlc_to_review_proto(odlc)),
content_type="application/json")
示例15: dispatch
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import HttpResponseNotFound [as 别名]
def dispatch(self, request, *args, **kwargs):
slug = self.kwargs['slug']
try:
bill = self.model.objects.get(slug=slug)
response = super().dispatch(request, *args, **kwargs)
except NYCBill.DoesNotExist:
bill = None
if bill is None:
try:
bill = self.model.objects.get(slug__startswith=slug)
response = HttpResponsePermanentRedirect(reverse('bill_detail', args=[bill.slug]))
except NYCBill.DoesNotExist:
try:
one, two, three, four = slug.split('-')
short_slug = slug.replace('-' + four, '')
bill = self.model.objects.get(slug__startswith=short_slug)
response = HttpResponsePermanentRedirect(reverse('bill_detail', args=[bill.slug]))
except:
response = HttpResponseNotFound()
return response