Python django.http.HttpResponseNotAllowed() Examples

The following are 30 code examples for showing how to use django.http.HttpResponseNotAllowed(). 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: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 6 votes vote down vote up
def contacts_new(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(('POST',))

    data = {
        key: value for key, value in request.POST.items()
        if key in ('name', 'fone', 'email')
    }
    contact = Contact.objects.create(**data)
    response = dict(
        name=contact.name,
        avatar=contact.avatar(),
        email=contact.email,
        phone=contact.fone
    )

    return JsonResponse(response, status=201) 
Example 2
Project: monasca-ui   Author: openstack   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def dispatch(self, request, url):
        if not url:
            url = '/'

        if request.method not in self.http_method_names:
            return http.HttpResponseNotAllowed(request.method)

        if not self._can_access_kibana():
            error_msg = (_('User %s does not have sufficient '
                           'privileges to access Kibana')
                         % auth_utils.get_user(request))
            LOG.error(error_msg)
            return http.HttpResponseForbidden(content=error_msg)

        # passing kbn version explicitly for kibana >= 4.3.x
        headers = {
            "X-Auth-Token": request.user.token.id,
            "kbn-version": request.META.get("HTTP_KBN_VERSION", ""),
            "Cookie": request.META.get("HTTP_COOKIE", ""),
            "Content-Type": "application/json",
        }

        return self.read(request.method, url, request.body, headers) 
Example 3
Project: bioforum   Author: reBiocoder   File: http.py    License: MIT License 6 votes vote down vote up
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    extra={'status_code': 405, 'request': request}
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator 
Example 4
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def webhook(request, build_key):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    try:
        data = json.loads(request.body)
    except ValueError:
        err_str = "Bad json in github webhook request"
        logger.warning(err_str)
        return HttpResponseBadRequest(err_str)

    user = models.GitUser.objects.filter(build_key=build_key).first()
    if not user:
        logger.warning("No user with build key %s" % build_key)
        return HttpResponseBadRequest("Error")

    if user.recipes.count() == 0:
        logger.warning("User '%s' does not have any recipes" % user)
        return HttpResponseBadRequest("Error")

    return process_event(user, data) 
Example 5
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def do_branch_page(request, branch):
    """
    Render the branch page given a branch object
    Input:
        request[django.http.HttpRequest]
        branch[models.Branch]
    """
    if request.method != "GET":
        return HttpResponseNotAllowed(['GET'])

    causes = []
    if request.GET.get("do_filter", "0") == "0":
        causes = [models.Event.PUSH, models.Event.MANUAL, models.Event.RELEASE]
        form = forms.BranchEventsForm(initial={"filter_events": causes})
    else:
        form = forms.BranchEventsForm(request.GET)
        if form.is_valid():
            causes = [int(c) for c in form.cleaned_data["filter_events"]]

    event_list = EventsStatus.get_default_events_query().filter(base__branch=branch, cause__in=causes)
    events = get_paginated(request, event_list)
    evs_info = EventsStatus.multiline_events_info(events)
    return render(request, 'ci/branch.html', {"form": form, 'branch': branch, 'events': evs_info, 'pages': events}) 
Example 6
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def activate_job(request, job_id):
    """
    Endpoint for activating a job
    """
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    job = get_object_or_404(models.Job, pk=job_id)
    server = job.recipe.repository.server()
    user = server.signed_in_user(request.session)
    if not user:
        raise PermissionDenied('You need to be signed in to activate a job')

    collab = Permissions.is_collaborator(request.session, job.event.build_user, job.recipe.repository, user=user)
    if collab:
        if set_job_active(request, job, user):
            job.init_pr_status()
        job.event.make_jobs_ready()
    else:
        raise PermissionDenied('Activate job: {} is NOT a collaborator on {}'.format(user, job.recipe.repository))

    return redirect('ci:view_job', job_id=job.pk) 
Example 7
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def cancel_job(request, job_id):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    job = get_object_or_404(models.Job, pk=job_id)
    allowed = Permissions.is_collaborator(request.session, job.event.build_user, job.event.base.repo())
    if not allowed:
        return HttpResponseForbidden('Not allowed to cancel this job')

    signed_in_user = job.event.base.server().signed_in_user(request.session)
    message = "Canceled by %s" % signed_in_user
    comment = escape(request.POST.get('comment'))

    post_to_pr = request.POST.get('post_to_pr') == 'on'
    if post_to_pr:
        post_job_change_to_pr(request, job, "canceled", comment, signed_in_user)

    if comment:
        message += "\nwith comment: %s" % comment
    set_job_canceled(job, message)
    UpdateRemoteStatus.job_complete(job)
    logger.info('Job {}: {} on {} canceled by {}'.format(job.pk, job, job.recipe.repository, signed_in_user))
    messages.info(request, 'Job {} canceled'.format(job))
    return redirect('ci:view_job', job_id=job.pk) 
Example 8
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def update_remote_job_status(request, job_id):
    """
    End point for manually update the remote status of a job.
    This is needed since sometimes the git server doesn't
    get updated properly due to timeouts, etc.
    """
    job = get_object_or_404(models.Job.objects, pk=job_id)
    allowed = Permissions.is_collaborator(request.session, job.event.build_user, job.event.base.repo())

    if request.method == "GET":
        return render(request, 'ci/job_update.html', {"job": job, "allowed": allowed})
    elif request.method == "POST":
        if allowed:
            UpdateRemoteStatus.job_complete_pr_status(job)
        else:
            return HttpResponseNotAllowed("Not allowed")
    return redirect('ci:view_job', job_id=job.pk) 
Example 9
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def webhook(request, build_key):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    try:
        data = json.loads(request.body)
    except ValueError:
        err_str = "Bad json in github webhook request"
        logger.warning(err_str)
        return HttpResponseBadRequest(err_str)

    user = models.GitUser.objects.filter(build_key=build_key).first()
    if not user:
        logger.warning("No user with build key %s" % build_key)
        return HttpResponseBadRequest("Error")

    if user.recipes.count() == 0:
        logger.warning("User '%s' does not have any recipes" % user)
        return HttpResponseBadRequest("Error")

    return process_event(user, data) 
Example 10
Project: crash   Author: mmohrhard   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def upload_symbols(request):

    if request.method != 'POST':
        return HttpResponseNotAllowed('Only POST here')

    form = UploadSymbolsForm(request.POST, request.FILES)

    if not form.is_valid():
        logger.error("form is invalid with error: " + str(form.errors))
        return HttpResponseNotAllowed('Invalid data')

    path = handle_uploaded_file(request.FILES['symbols'])
    upload = SymbolsUploadHandler()
    upload.process(form.cleaned_data, path)

    return HttpResponse("Success") 
Example 11
Project: crash   Author: mmohrhard   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def upload_file(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed('Only POST here')

    form = UploadFileForm(request.POST, request.FILES)

    if not form.is_valid():
        logger.error("form is invalid with error: " + str(form.errors))
        return HttpResponseBadRequest()

    file = request.FILES['upload_file_minidump']

    try:
        crash_id = str(create_database_entry(file, form))
    except (InvalidVersionException) as e:
        logger.error("invalid version exception " + str(e))
        return HttpResponseServerError(str(e))

    logger.info("uploaded crash: " + crash_id)
    return HttpResponse('Crash-ID=%s'%(crash_id))

# vim:set shiftwidth=4 softtabstop=4 expandtab: */ 
Example 12
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: http.py    License: MIT License 6 votes vote down vote up
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                response = HttpResponseNotAllowed(request_method_list)
                log_response(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    response=response,
                    request=request,
                )
                return response
            return func(request, *args, **kwargs)
        return inner
    return decorator 
Example 13
Project: python   Author: Yeah-Kun   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    extra={'status_code': 405, 'request': request}
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator 
Example 14
Project: luscan-devel   Author: blackye   File: http.py    License: GNU General Public License v2.0 6 votes vote down vote up
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
                    extra={
                        'status_code': 405,
                        'request': request
                    }
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator 
Example 15
Project: openhgsenti   Author: drexly   File: http.py    License: Apache License 2.0 6 votes vote down vote up
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
                    extra={
                        'status_code': 405,
                        'request': request
                    }
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator 
Example 16
Project: python2017   Author: bpgc-cte   File: http.py    License: MIT License 6 votes vote down vote up
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can assume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    extra={'status_code': 405, 'request': request}
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator 
Example 17
Project: govready-q   Author: GovReady   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def authoring_tool_auth(f):
    def g(request):
        if request.method != "POST":
            return HttpResponseNotAllowed(["POST"])

        # Get the task and question and check permissions.

        task = get_object_or_404(Task, id=request.POST["task"])
        if not task.has_write_priv(request.user):
            return HttpResponseForbidden()
        if not task.module.is_authoring_tool_enabled(request.user):
            return HttpResponseForbidden()

        # Run inner function.
        return f(request, task)

    return g 
Example 18
Project: hypha   Author: OpenTechFund   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self, request, type, submission_pk):
        if not request.is_ajax():
            return HttpResponseNotAllowed()

        # Only staff can create staff flags.
        if type == self.model.STAFF and not self.request.user.is_apply_staff:
            return HttpResponseNotAllowed()

        submission_type = ContentType.objects.get_for_model(ApplicationSubmission)
        # Trying to get a flag from the table, or create a new one
        flag, created = self.model.objects.get_or_create(user=request.user, target_object_id=submission_pk, target_content_type=submission_type, type=type)
        # If no new flag has been created,
        # Then we believe that the request was to delete the flag.
        if not created:
            flag.delete()

        return JsonResponse({"result": created}) 
Example 19
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_require_safe_accepts_only_safe_methods(self):
        """
        Test for the require_safe decorator.
        A view returns either a response or an exception.
        Refs #15637.
        """
        def my_view(request):
            return HttpResponse("OK")
        my_safe_view = require_safe(my_view)
        request = HttpRequest()
        request.method = 'GET'
        self.assertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'HEAD'
        self.assertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'POST'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'PUT'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'DELETE'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)


# For testing method_decorator, a decorator that assumes a single argument.
# We will get type arguments if there is a mismatch in the number of arguments. 
Example 20
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_require_safe_accepts_only_safe_methods(self):
        """
        Test for the require_safe decorator.
        A view returns either a response or an exception.
        Refs #15637.
        """
        def my_view(request):
            return HttpResponse("OK")
        my_safe_view = require_safe(my_view)
        request = HttpRequest()
        request.method = 'GET'
        self.assertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'HEAD'
        self.assertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'POST'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'PUT'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'DELETE'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)


# For testing method_decorator, a decorator that assumes a single argument.
# We will get type arguments if there is a mismatch in the number of arguments. 
Example 21
Project: HELPeR   Author: dschep   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def dispatch_task_pair_url(request, task_pair_id, secret):
    task_pair = get_object_or_404(TaskPair, id=task_pair_id)
    try:
        if request.method == 'POST':
            view = task_pair.cause_view
            assert task_pair.cause_agent.options.get('secret') == secret
        elif request.method == 'GET':
            view = task_pair.effect_view
            assert task_pair.effect_agent.options.get('secret') == secret
        else:
            return HttpResponseNotAllowed(['POST', 'GET'])
    except (AttributeError, ImportError):
        raise Http404
    except AssertionError:
        return HttpResponseForbidden()
    else:
        return view(request, task_pair) 
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: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
            extra={
                'status_code': 405,
                'request': request
            }
        )
        return http.HttpResponseNotAllowed(self._allowed_methods()) 
Example 25
Project: kobo-predict   Author: awemulya   File: middleware.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_response(self, request, response):
        if isinstance(response, HttpResponseNotAllowed):
            context = RequestContext(request)
            response.content = loader.render_to_string(
                "405.html", context_instance=context)

        return response 
Example 26
Project: django_reddit   Author: nikolak   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def post_only(func):# pragma: no cover
    def decorated(request, *args, **kwargs):
        if request.method != 'POST':
            return HttpResponseNotAllowed(['GET'])
        return func(request, *args, **kwargs)
    return decorated 
Example 27
Project: django_reddit   Author: nikolak   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def get_only(func):# pragma: no cover
    def decorated(request, *args, **kwargs):
        if request.method != 'GET':
            return HttpResponseNotAllowed(['POST'])
        return func(request, *args, **kwargs)
    return decorated 
Example 28
Project: django_reddit   Author: nikolak   File: test_comments.py    License: Apache License 2.0 5 votes vote down vote up
def test_post_only(self):
        r = self.c.get(reverse('post_comment'))
        self.assertIsInstance(r, HttpResponseNotAllowed) 
Example 29
Project: DeerU   Author: gojuukaze   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def upload_image_view(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['GET', 'POST'])
    file = request.FILES.get('file')
    try:
        from PIL import Image as pil_image
        pil_image.open(file).verify()
    except:
        if not file.name.endswith('.svg'):
            return JsonResponse({'error': '无法识别图片'})

    album = create_image(file.name, file)

    return JsonResponse({'msg': '上传成功!', 'link': album.img.url}) 
Example 30
Project: django-admino   Author: erdem   File: sites.py    License: MIT License 5 votes vote down vote up
def http_method_not_allowed(self, request, *args, **kwargs):
        if settings.DEBUG and self._allowed_methods():
            raise Exception("Only" + str(self._allowed_methods()))
        return http.HttpResponseNotAllowed(self._allowed_methods())