Python django.http.HttpResponseNotFound() Examples

The following are 30 code examples for showing how to use django.http.HttpResponseNotFound(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: arches   Author: archesproject   File: main.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example 2
Project: arches   Author: archesproject   File: graph.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example 3
Project: arches   Author: archesproject   File: graph.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request):
        nodegroupid = None
        try:
            nodegroupid = uuid.UUID(str(request.POST.get("nodegroupid")))
        except Exception as e:
            print(e)
        if self.action == "exportable" and nodegroupid is not None:
            exportable = json.loads(request.POST.get("exportable"))

            nodegroup = models.NodeGroup.objects.select_for_update().filter(nodegroupid=nodegroupid)
            with transaction.atomic():
                for ng in nodegroup:
                    ng.exportable = exportable
                    ng.save()

            return JSONResponse({"nodegroup": nodegroupid, "status": "success"})

        return HttpResponseNotFound() 
Example 4
Project: arches   Author: archesproject   File: mobile_survey.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example 5
Project: arches   Author: archesproject   File: mobile_survey.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, request, surveyid):
        try:
            connection_error = False
            with transaction.atomic():
                if surveyid is not None:
                    ret = MobileSurvey.objects.get(pk=surveyid)
                    ret.delete()
                    return JSONResponse({"success": True})
        except Exception as e:
            if connection_error is False:
                error_title = _("Unable to delete survey")
                if "strerror" in e and e.strerror == "Connection refused" or "Connection refused" in e:
                    error_message = _("Unable to connect to CouchDB. Please confirm that CouchDB is running")
                else:
                    error_message = e.message
                connection_error = JSONErrorResponse(error_title, error_message)
            return connection_error

        return HttpResponseNotFound() 
Example 6
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example 7
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 8
Project: AnsibleUI   Author: lotus-dgas   File: Proxy.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 9
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 10
Project: kobo-predict   Author: awemulya   File: tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example 11
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
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") 
Example 12
Project: zulip   Author: zulip   File: documentation.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 13
Project: oh-my-rss   Author: richshaw2015   File: views_api.py    License: MIT License 6 votes vote down vote up
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") 
Example 14
Project: oh-my-rss   Author: richshaw2015   File: views_html.py    License: MIT License 6 votes vote down vote up
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) 
Example 15
Project: interop   Author: auvsi-suas   File: odlcs.py    License: Apache License 2.0 6 votes vote down vote up
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.") 
Example 16
Project: interop   Author: auvsi-suas   File: odlcs.py    License: Apache License 2.0 6 votes vote down vote up
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") 
Example 17
Project: nyc-councilmatic   Author: datamade   File: views.py    License: MIT License 6 votes vote down vote up
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 
Example 18
Project: nyc-councilmatic   Author: datamade   File: views.py    License: MIT License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        slug = self.kwargs['slug']

        try:
            committee = self.model.objects.get(slug=slug)
            response = super().dispatch(request, *args, **kwargs)
        except Organization.DoesNotExist:
            committee = None

        if committee is None:
            try:
                slug = slug.replace(',', '').replace('\'', '')
                committee = self.model.objects.get(slug__startswith=slug)
                response = HttpResponsePermanentRedirect(reverse('committee_detail', args=[committee.slug]))
            except Organization.DoesNotExist:
                response = HttpResponseNotFound()

        return response 
Example 19
Project: django-leonardo   Author: django-leonardo   File: defaults.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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/')
    """
    response = render_in_page(request, template_name)

    if response:
        return response

    template = Template(
        '<h1>Not Found</h1>'
        '<p>The requested URL {{ request_path }} was not found on this server.</p>')
    body = template.render(RequestContext(
        request, {'request_path': request.path}))
    return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE) 
Example 20
Project: mrs   Author: betagouv   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        self.institution = Institution.objects.filter(
            finess=kwargs['finess']
        ).first()

        if not self.institution:
            return http.HttpResponseNotFound()

        # this is for security implemented in javascript (PMT upload)
        if self.institution.dynamic_allow:
            if 'origin' not in request.GET:
                return http.HttpResponseBadRequest('"origin" required in GET')
            origin = request.GET['origin']
        else:
            origin = self.institution.origin

        self.allow_origin = '/'.join(origin.split('/')[:3])
        response = super().dispatch(request, *args, **kwargs)
        response.allow_origin = self.allow_origin
        return response 
Example 21
Project: arches   Author: archesproject   File: graph.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def delete(self, request, graphid):
        if self.action == "delete_node":
            data = JSONDeserializer().deserialize(request.body)
            try:
                graph = Graph.objects.get(graphid=graphid)
                graph.delete_node(node=data.get("nodeid", None))
                return JSONResponse({})
            except GraphValidationError as e:
                return JSONErrorResponse(e.title, e.message)
        elif self.action == "delete_instances":
            try:
                graph = Graph.objects.get(graphid=graphid)
                graph.delete_instances()
                return JSONResponse(
                    {
                        "success": True,
                        "message": "All the resources associated with the Model '{0}' have been successfully deleted.".format(graph.name),
                        "title": "Resources Successfully Deleted.",
                    }
                )
            except GraphValidationError as e:
                return JSONErrorResponse(e.title, e.message)
            except ModelInactiveError as e:
                return JSONErrorResponse(e.title, e.message)
        elif self.action == "delete_graph":
            try:
                graph = Graph.objects.get(graphid=graphid)
                if graph.isresource:
                    graph.delete_instances()
                    graph.isactive = False
                    graph.save(validate=False)
                graph.delete()
                return JSONResponse({"success": True})
            except GraphValidationError as e:
                return JSONErrorResponse(e.title, e.message)

        return HttpResponseNotFound() 
Example 22
Project: arches   Author: archesproject   File: concept.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def manage_parents(request, conceptid):
    if request.method == "POST":
        json = request.body
        if json is not None:
            data = JSONDeserializer().deserialize(json)

            with transaction.atomic():
                if len(data["deleted"]) > 0:
                    concept = Concept().get(id=conceptid, include=None)
                    for deleted in data["deleted"]:
                        concept.addparent(deleted)

                    concept.delete()
                    concept.bulk_index()

                if len(data["added"]) > 0:
                    concept = Concept().get(id=conceptid)
                    for added in data["added"]:
                        concept.addparent(added)

                    concept.save()
                    concept.bulk_index()

            return JSONResponse(data)

    else:
        return HttpResponseNotAllowed(["POST"])

    return HttpResponseNotFound() 
Example 23
Project: arches   Author: archesproject   File: concept.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def add_concepts_from_sparql_endpoint(request, conceptid):
    if request.method == "POST":
        json = request.body
        if json is not None:
            data = JSONDeserializer().deserialize(json)

            parentconcept = Concept({"id": conceptid, "nodetype": data["model"]["nodetype"]})

            if parentconcept.nodetype == "Concept":
                relationshiptype = "narrower"
            elif parentconcept.nodetype == "ConceptScheme":
                relationshiptype = "hasTopConcept"

            provider = get_sparql_providers(data["endpoint"])
            try:
                parentconcept.subconcepts = provider.get_concepts(data["ids"])
            except Exception as e:
                return HttpResponseServerError(e.message)

            for subconcept in parentconcept.subconcepts:
                subconcept.relationshiptype = relationshiptype

            parentconcept.save()
            parentconcept.index()

            return JSONResponse(parentconcept, indent=4)

    else:
        return HttpResponseNotAllowed(["POST"])

    return HttpResponseNotFound() 
Example 24
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, resourceid=None, formid=None):
        if formid is not None:
            form = Form(resourceid=resourceid, formid=formid, user=request.user)
            return JSONResponse(form)

        return HttpResponseNotFound() 
Example 25
Project: PrivacyScore   Author: PrivacyScore   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
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') 
Example 26
Project: sentry-python   Author: getsentry   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handler404(*args, **kwargs):
    sentry_sdk.capture_message("not found", level="error")
    return HttpResponseNotFound("404") 
Example 27
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def download_metadata(request, username, id_string, data_id):
    xform = get_object_or_404(XForm,
                              user__username__iexact=username,
                              id_string__exact=id_string)
    owner = xform.user
    if username == request.user.username or xform.shared:
        data = get_object_or_404(MetaData, pk=data_id)
        file_path = data.data_file.name
        filename, extension = os.path.splitext(file_path.split('/')[-1])
        extension = extension.strip('.')
        dfs = get_storage_class()()
        if dfs.exists(file_path):
            audit = {
                'xform': xform.id_string
            }
            audit_log(
                Actions.FORM_UPDATED, request.user, owner,
                _("Document '%(filename)s' for '%(id_string)s' downloaded.") %
                {
                    'id_string': xform.id_string,
                    'filename': "%s.%s" % (filename, extension)
                }, audit, request)
            response = response_with_mimetype_and_name(
                data.data_file_type,
                filename, extension=extension, show_date=False,
                file_path=file_path)
            return response
        else:
            return HttpResponseNotFound()

    return HttpResponseForbidden(_(u'Permission denied.')) 
Example 28
Project: yata   Author: Kivou-2000607   File: handy.py    License: GNU General Public License v3.0 5 votes vote down vote up
def returnError(type=500, exc=None, msg=None, home=True, session=None):
    import traceback
    from django.utils import timezone
    from django.http import HttpResponseServerError
    from django.http import HttpResponseForbidden
    from django.http import HttpResponseNotFound
    from django.template.loader import render_to_string
    from player.models import Player

    if type == 403:
        msg = "Permission Denied" if msg is None else msg
        return HttpResponseForbidden(render_to_string('403.html', {'exception': msg, 'home': home}))
    if type == 404:
        msg = "Not Found" if msg is None else msg
        return HttpResponseNotFound(render_to_string('404.html', {'exception': msg, 'home': home}))
    else:
        message = traceback.format_exc().strip()
        print("[{:%d/%b/%Y %H:%M:%S}] ERROR 500 \n{}".format(timezone.now(), message))
        if session is not None and session.get("player", False):
            player = getPlayer(session["player"].get("tId"))
        else:
            player = Player.objects.filter(tId=-1).first()
        defaults = {"timestamp": tsnow()}
        try:
            player.error_set.update_or_create(short_error=exc, long_error=message, defaults=defaults)
        except BaseException as e:
            print("Meta error", e)
        return HttpResponseServerError(render_to_string('500.html', {'exception': exc, 'home': home})) 
Example 29
Project: django-useraudit   Author: muccg   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_request_available(request):
    thread_request = middleware.get_request()
    if thread_request == request:
        return HttpResponse('OK')
    return HttpResponseNotFound() 
Example 30
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def check_identifier_available(request):
    """
    Given a Spark job identifier checks if one already exists.
    """
    form = SparkJobAvailableForm(request.GET)
    if form.is_valid():
        identifier = form.cleaned_data["identifier"]
        if SparkJob.objects.filter(identifier=identifier).exists():
            response = HttpResponse("identifier unavailable")
        else:
            response = HttpResponseNotFound("identifier available")
    else:
        response = HttpResponseNotFound("identifier invalid")
    return response