當前位置: 首頁>>代碼示例>>Python>>正文


Python http.HttpResponseNotFound方法代碼示例

本文整理匯總了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() 
開發者ID:archesproject,項目名稱:arches,代碼行數:18,代碼來源:main.py

示例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() 
開發者ID:archesproject,項目名稱:arches,代碼行數:20,代碼來源:graph.py

示例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() 
開發者ID:archesproject,項目名稱:arches,代碼行數:27,代碼來源:mobile_survey.py

示例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() 
開發者ID:archesproject,項目名稱:arches,代碼行數:24,代碼來源:resource.py

示例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) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:23,代碼來源:gaeunit.py

示例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 
開發者ID:lotus-dgas,項目名稱:AnsibleUI,代碼行數:24,代碼來源:Proxy.py

示例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) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:23,代碼來源:defaults.py

示例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) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:20,代碼來源:tools.py

示例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") 
開發者ID:znick,項目名稱:anytask,代碼行數:21,代碼來源:views.py

示例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) 
開發者ID:zulip,項目名稱:zulip,代碼行數:24,代碼來源:documentation.py

示例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") 
開發者ID:richshaw2015,項目名稱:oh-my-rss,代碼行數:22,代碼來源:views_api.py

示例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) 
開發者ID:richshaw2015,項目名稱:oh-my-rss,代碼行數:27,代碼來源:views_html.py

示例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.") 
開發者ID:auvsi-suas,項目名稱:interop,代碼行數:22,代碼來源:odlcs.py

示例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") 
開發者ID:auvsi-suas,項目名稱:interop,代碼行數:23,代碼來源:odlcs.py

示例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 
開發者ID:datamade,項目名稱:nyc-councilmatic,代碼行數:25,代碼來源:views.py


注:本文中的django.http.HttpResponseNotFound方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。