Python django.http.HttpResponseNotFound() Examples

The following are 30 code examples of django.http.HttpResponseNotFound(). 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 also want to check out all available functions/classes of the module django.http , or try the search function .
Example #1
Source File: views.py    From mrs with 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 #2
Source File: gaeunit.py    From browserscope with 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 #3
Source File: Proxy.py    From AnsibleUI with 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 #4
Source File: graph.py    From arches with 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 #5
Source File: resource.py    From arches with 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 #6
Source File: mobile_survey.py    From arches with 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 #7
Source File: graph.py    From arches with 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 #8
Source File: mobile_survey.py    From arches with 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 #9
Source File: defaults.py    From GTDWeb with 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
Source File: tools.py    From kobo-predict with 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
Source File: views.py    From anytask with 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
Source File: documentation.py    From zulip with 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
Source File: main.py    From arches with 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 #14
Source File: defaults.py    From django-leonardo with 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 #15
Source File: views.py    From nyc-councilmatic with 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 #16
Source File: views.py    From nyc-councilmatic with 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 #17
Source File: odlcs.py    From interop with 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 #18
Source File: odlcs.py    From interop with 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 #19
Source File: views_html.py    From oh-my-rss with 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 #20
Source File: views_api.py    From oh-my-rss with 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 #21
Source File: index_view.py    From black-widow with GNU General Public License v3.0 6 votes vote down vote up
def static(request, path):
    """
    Manage requested static file (for non-DEBUG mode compatibility without web-server)
    :type request: django.core.handlers.wsgi.WSGIRequest
    :type path: str
    :rtype: django.http.HttpResponse
    """
    for directory in STATICFILES_DIRS:
        static_file = os.path.join(directory, path)
        if os.path.isfile(static_file):
            return FileResponse(open(static_file, 'rb'))
    return HttpResponseNotFound() 
Example #22
Source File: views.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        claim = get_object_or_404(Claim, pk=self.kwargs['pk'])
        if not self._can_request_user_see_claim(claim):
            return HttpResponseNotFound()
        return super(ClaimStatusView, self).get(request, *args, **kwargs) 
Example #23
Source File: odlcs.py    From interop with Apache License 2.0 5 votes vote down vote up
def get(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))

        if not odlc.thumbnail or not odlc.thumbnail.name:
            return HttpResponseNotFound('Odlc %s has no image' % pk)

        # Tell sendfile to serve the thumbnail.
        return sendfile(request, odlc.thumbnail.path) 
Example #24
Source File: odlcs.py    From interop with Apache License 2.0 5 votes vote down vote up
def put(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))

        odlc_proto = interop_api_pb2.Odlc()
        try:
            json_format.Parse(request.body, odlc_proto)
        except Exception as e:
            return HttpResponseBadRequest(
                'Failed to parse request. Error: %s' % str(e))
        # Validate ODLC proto fields.
        try:
            validate_odlc_proto(odlc_proto)
        except ValueError as e:
            return HttpResponseBadRequest(str(e))
        # ID provided in proto must match object.
        if odlc_proto.HasField('id') and odlc_proto.id != odlc.pk:
            return HttpResponseBadRequest('ID in request does not match URL.')

        # Update the ODLC object from the request.
        update_odlc_from_proto(odlc, odlc_proto)
        odlc.update_last_modified()
        odlc.save()

        return HttpResponse(json_format.MessageToJson(odlc_to_proto(odlc)),
                            content_type="application/json") 
Example #25
Source File: odlcs.py    From interop with Apache License 2.0 5 votes vote down vote up
def get(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))

        return HttpResponse(json_format.MessageToJson(odlc_to_proto(odlc)),
                            content_type="application/json") 
Example #26
Source File: views_api.py    From oh-my-rss with MIT License 5 votes vote down vote up
def leave_a_message(request):
    """
    添加留言
    """
    uid = request.POST.get('uid', '').strip()[:100]

    content = request.POST.get('content', '').strip()[:500]
    nickname = request.POST.get('nickname', '').strip()[:20]
    contact = request.POST.get('contact', '').strip()[:50]

    user = get_login_user(request)

    if content:
        try:
            msg = Message(uid=uid, content=content, nickname=nickname, contact=contact, user=user)
            msg.save()

            logger.warning(f"有新的留言:`{content}")

            return get_all_issues(request)
        except:
            logger.error(f"留言增加失败:`{uid}`{content}`{nickname}`{contact}")
            return HttpResponseServerError('Inter error')

    logger.warning(f"参数错误:`{content}")
    return HttpResponseNotFound("Param error") 
Example #27
Source File: views_api.py    From oh-my-rss with MIT License 5 votes vote down vote up
def submit_a_feed(request):
    """
    用户添加一个自定义的订阅源
    """
    feed_url = request.POST.get('url', '').strip()[:1024]
    user = get_login_user(request)

    if feed_url:
        host = get_host_name(feed_url)

        if 'ershicimi.com' in host:
            rsp = parse_wemp_ershicimi(feed_url)
        elif host in settings.ALLOWED_HOSTS:
            rsp = parse_self_atom(feed_url)
        else:
            rsp = parse_atom(feed_url)

        if rsp:
            logger.warning(f"有新订阅源被提交:`{feed_url}")

            # 已登录用户,自动订阅
            if user:
                add_user_sub_feeds(user.oauth_id, [rsp['name'], ])
            return JsonResponse(rsp)
        else:
            logger.warning(f"RSS 解析失败:`{feed_url}")

    return HttpResponseNotFound("Param error") 
Example #28
Source File: views_api.py    From oh-my-rss with MIT License 5 votes vote down vote up
def user_unsubscribe_feed(request):
    """
    已登录用户取消订阅源
    """
    feed = request.POST.get('feed', '').strip()[:32]

    user = get_login_user(request)

    if user and feed:
        del_user_sub_feed(user.oauth_id, feed)

        logger.warning(f"登陆用户取消订阅动作:`{user.oauth_name}`{feed}")

        return JsonResponse({"name": feed})
    return HttpResponseNotFound("Param error") 
Example #29
Source File: concept.py    From arches with 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 #30
Source File: views_html.py    From oh-my-rss with MIT License 5 votes vote down vote up
def get_recommend_articles(request):
    """
    获取文章推荐的订阅源,只开放登录用户
    :param request:
    :return:
    """
    uindex = int(request.POST['id'])
    user = get_login_user(request)

    if uindex and user:
        recommend_articles = []
        relative_articles = list(get_similar_article(uindex).keys())
        user_sub_feeds = get_user_sub_feeds(user.oauth_id)

        for relative_uindex in relative_articles:
            try:
                article = Article.objects.get(uindex=relative_uindex)
            except:
                continue

            if article.site.name not in user_sub_feeds:
                recommend_articles.append(article)
            if len(recommend_articles) >= 3:
                break

        if recommend_articles:
            logger.info(f'推荐数据条数:`{len(recommend_articles)}`{user.oauth_name}')

            context = dict()
            context['recommend_articles'] = recommend_articles

            return render(request, 'recommend/relative_article.html', context=context)

    return HttpResponseNotFound("No Recommend Data")