Python django.http.HttpResponseNotAllowed() Examples

The following are 30 code examples of django.http.HttpResponseNotAllowed(). 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: http.py    From python with 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 #2
Source File: views.py    From civet with 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 #3
Source File: views.py    From govready-q with 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 #4
Source File: views.py    From civet with 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
Source File: views.py    From civet with 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 #6
Source File: http.py    From python2017 with 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 #7
Source File: views.py    From civet with 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 #8
Source File: views.py    From crash with 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 #9
Source File: views.py    From hypha with 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 #10
Source File: views.py    From civet with 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 #11
Source File: http.py    From openhgsenti with 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 #12
Source File: views.py    From civet with 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 #13
Source File: tests.py    From djongo with 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 #14
Source File: http.py    From Hands-On-Application-Development-with-PyCharm with 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 #15
Source File: http.py    From luscan-devel with 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 #16
Source File: views.py    From monasca-ui with 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 #17
Source File: views.py    From django-ajax-contacts with 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 #18
Source File: views.py    From crash with 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 #19
Source File: views.py    From HELPeR with 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 #20
Source File: http.py    From bioforum with 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 #21
Source File: tests.py    From djongo with 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 #22
Source File: base.py    From openhgsenti with Apache License 2.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 #23
Source File: base.py    From python2017 with MIT License 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 #24
Source File: base.py    From python with Apache License 2.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
Source File: base.py    From luscan-devel with 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': self.request
            }
        )
        return http.HttpResponseNotAllowed(self._allowed_methods()) 
Example #26
Source File: __init__.py    From graphql-django-view with MIT License 5 votes vote down vote up
def execute_graphql_request(self, request):
        query, variables, operation_name = self.get_graphql_params(request, self.parse_body(request))

        if not query:
            raise HttpError(HttpResponseBadRequest('Must provide query string.'))

        source = Source(query, name='GraphQL request')

        try:
            document_ast = parse(source)
            validation_errors = validate(self.schema, document_ast)
            if validation_errors:
                return ExecutionResult(
                    errors=validation_errors,
                    invalid=True,
                )
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True)

        if request.method.lower() == 'get':
            operation_ast = get_operation_ast(document_ast, operation_name)
            if operation_ast and operation_ast.operation != 'query':
                raise HttpError(HttpResponseNotAllowed(
                    ['POST'], 'Can only perform a {} operation from a POST request.'.format(operation_ast.operation)
                ))

        try:
            return self.execute(
                document_ast,
                root_value=self.get_root_value(request),
                variable_values=variables,
                operation_name=operation_name,
                context_value=self.get_context(request),
                executor=self.executor,
            )
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True) 
Example #27
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def test_thread_unsubscribe_view_only_accepts_post(self):
        """view should return HttpResponseNotAllowed if request isn't POST."""
        def check_http_method(method, klass):
            """Check HTTP functions"""
            request = getattr(self.request_factory, method)('/')
            request = patch_message_middleware(request)
            request.user = self.staff_user
            result = views.thread_unsubscribe_view(request, self.thread1.pk)
            self.assertIsInstance(result, klass)

        for method in ('put', 'get', 'head', 'delete', 'options'):
            check_http_method(method, HttpResponseNotAllowed)

        check_http_method('post', HttpResponse) 
Example #28
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def test_message_flag_view_only_accepts_post(self):
        """view should return HttpResponseNotAllowed if request isn't POST."""
        def check_http_method(method, klass):
            """Check HTTP functions"""
            request = getattr(self.request_factory, method)('/')
            request.user = self.staff_user
            result = views.message_flag_view(request, self.message1.pk)
            self.assertIsInstance(result, klass)

        for method in ('put', 'get', 'head', 'delete', 'options'):
            check_http_method(method, HttpResponseNotAllowed)

        check_http_method('post', HttpResponse) 
Example #29
Source File: views.py    From mapstory with GNU General Public License v3.0 5 votes vote down vote up
def flag(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed('Only POST requests are supported.')

    content_type = request.POST.get("content_type")
    object_id = request.POST.get("object_id")
    creator_field = request.POST.get("creator_field")
    comment = request.POST.get("comment")
    next = request.POST.get("next")
    flag_type = request.POST.get("flag_type", None)

    content_type = get_object_or_404(ContentType, id=int(content_type))
    object_id = int(object_id)

    content_object = content_type.get_object_for_this_type(id=object_id)

    if creator_field and hasattr(content_object, creator_field):
        creator = getattr(content_object, creator_field)
    else:
        creator = None

    add_flag(request.user, content_type, object_id,
             creator, comment, flag_type=flag_type)
    messages.success(request, _(
        "You have added a flag. A moderator will review your submission shortly."), fail_silently=True)

    if next:
        return HttpResponseRedirect(next)
    else:
        return HttpResponseRedirect(reverse('flag-reported')) 
Example #30
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def test_not_post(self):
        """View should only accept POST requests."""
        someone = self.create_user(is_staff=True)
        group = Group.objects.create(name='test')
        user = self.create_user()
        user.add_to_group(group.pk)
        self.client.login(username=someone.email, password='moo')
        response = self.client.get(
            reverse('remove_user_from_group',
                    kwargs={'group_id': group.pk, 'user_uuid': user.uuid})
        )
        self.assertIsInstance(response, HttpResponseNotAllowed)