Python django.http.response.HttpResponseBadRequest() Examples

The following are 17 code examples of django.http.response.HttpResponseBadRequest(). 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.response , or try the search function .
Example #1
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def remove(self, request: WSGIRequest) -> HttpResponse:
        """Removes a song identified by the given key from the queue."""
        key = request.POST.get("key")
        if key is None:
            return HttpResponseBadRequest()
        ikey = int(key)
        try:
            removed = self.playback.queue.remove(ikey)
            self.playback.queue_semaphore.acquire(blocking=False)
            # if we removed a song and it was added by autoplay,
            # we want it to be the new basis for autoplay
            if not removed.manually_requested:
                self.playback.handle_autoplay(removed.external_url or removed.title)
            else:
                self.playback.handle_autoplay()
        except models.QueuedSong.DoesNotExist:
            return HttpResponseBadRequest("song does not exist")
        return HttpResponse() 
Example #2
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def reorder(self, request: WSGIRequest) -> HttpResponse:
        """Reorders the queue.
        The song specified by element is inserted between prev and next."""
        prev_key = request.POST.get("prev")
        cur_key = request.POST.get("element")
        next_key = request.POST.get("next")
        if not cur_key:
            return HttpResponseBadRequest()
        if not prev_key:
            iprev_key = None
        else:
            iprev_key = int(prev_key)
        icur_key = int(cur_key)
        if not next_key:
            inext_key = None
        else:
            inext_key = int(next_key)
        try:
            self.playback.queue.reorder(iprev_key, icur_key, inext_key)
        except ValueError:
            return HttpResponseBadRequest("request on old state")
        return HttpResponse() 
Example #3
Source File: views.py    From graphene-django with MIT License 6 votes vote down vote up
def get_graphql_params(request, data):
        query = request.GET.get("query") or data.get("query")
        variables = request.GET.get("variables") or data.get("variables")
        id = request.GET.get("id") or data.get("id")

        if variables and isinstance(variables, six.text_type):
            try:
                variables = json.loads(variables)
            except Exception:
                raise HttpError(HttpResponseBadRequest("Variables are invalid JSON."))

        operation_name = request.GET.get("operationName") or data.get("operationName")
        if operation_name == "null":
            operation_name = None

        return query, variables, operation_name, id 
Example #4
Source File: __init__.py    From graphql-django-view with MIT License 6 votes vote down vote up
def parse_body(self, request):
        content_type = self.get_content_type(request)

        if content_type == 'application/graphql':
            return {'query': request.body.decode()}

        elif content_type == 'application/json':
            try:
                request_json = json.loads(request.body.decode('utf-8'))
                assert isinstance(request_json, dict)
                return request_json
            except:
                raise HttpError(HttpResponseBadRequest('POST body sent invalid JSON.'))

        elif content_type in ['application/x-www-form-urlencoded', 'multipart/form-data']:
            return request.POST

        return {} 
Example #5
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def prioritize(self, request: WSGIRequest) -> HttpResponse:
        """Prioritizes song by making it the first one in the queue."""
        key = request.POST.get("key")
        if key is None:
            return HttpResponseBadRequest()
        ikey = int(key)
        self.playback.queue.prioritize(ikey)
        return HttpResponse() 
Example #6
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def vote_up(self, request: WSGIRequest) -> HttpResponse:
        """Increases the vote-count of the given song by one."""
        key = request.POST.get("key")
        if key is None:
            return HttpResponseBadRequest()
        ikey = int(key)

        models.CurrentSong.objects.filter(queue_key=ikey).update(votes=F("votes") + 1)
        self.playback.queue.vote_up(ikey)
        return HttpResponse() 
Example #7
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def control(func: Callable) -> Callable:
    """A decorator for functions that control the playback.
    Every control changes the views state and returns an empty response."""

    def _decorator(
        self: "Controller", request: WSGIRequest, *args, **kwargs
    ) -> HttpResponse:
        # don't allow controls during alarm
        if self.playback.alarm_playing.is_set():
            return HttpResponseBadRequest()
        func(self, request, *args, **kwargs)
        self.musiq.update_state()
        return HttpResponse()

    return wraps(func)(_decorator) 
Example #8
Source File: admin.py    From django-translation-manager with Mozilla Public License 2.0 5 votes vote down vote up
def sync_translations(self, request):
        if not request.user.has_perm('translation_manager.sync'):
            return HttpResponseRedirect(reverse("admin:translation_manager_translationentry_changelist"))

        url = '{}?token={}'.format(
            get_settings('TRANSLATIONS_SYNC_REMOTE_URL'),
            get_settings('TRANSLATIONS_SYNC_REMOTE_TOKEN'),
        )

        remote_user = get_settings('TRANSLATIONS_SYNC_REMOTE_USER')
        remote_password = get_settings('TRANSLATIONS_SYNC_REMOTE_PASSWORD')

        if remote_user is not None and remote_password is not None:
            response = requests.get(url, verify=get_settings('TRANSLATIONS_SYNC_VERIFY_SSL'), auth=(remote_user, remote_password))
        else:
            response = requests.get(url, verify=get_settings('TRANSLATIONS_SYNC_VERIFY_SSL'))

        if not is_success(response.status_code):
            return HttpResponseBadRequest('Wrong response from remote TRM URL')

        data = response.json()

        RemoteTranslationEntry.objects.all().delete()

        for language, domains in data.items():
            for domain, translation_entries in domains.items():
                for original, translation_entry in translation_entries.items():
                    try:
                        main_entry = TranslationEntry.objects.get(language=language, original=original, domain=domain)
                    except TranslationEntry.DoesNotExist as e:
                        logger.debug('Missing: {} {} {}'.format(language, original, domain))
                        continue

                    RemoteTranslationEntry.objects.create(
                        translation=translation_entry['translation'],
                        changed=translation_entry['changed'],
                        translation_entry=main_entry
                    )

        return HttpResponseRedirect(reverse('admin:translation_manager_proxytranslationentry_changelist')) 
Example #9
Source File: views.py    From graphene-django with MIT License 5 votes vote down vote up
def parse_body(self, request):
        content_type = self.get_content_type(request)

        if content_type == "application/graphql":
            return {"query": request.body.decode()}

        elif content_type == "application/json":
            # noinspection PyBroadException
            try:
                body = request.body.decode("utf-8")
            except Exception as e:
                raise HttpError(HttpResponseBadRequest(str(e)))

            try:
                request_json = json.loads(body)
                if self.batch:
                    assert isinstance(request_json, list), (
                        "Batch requests should receive a list, but received {}."
                    ).format(repr(request_json))
                    assert (
                        len(request_json) > 0
                    ), "Received an empty list in the batch request."
                else:
                    assert isinstance(
                        request_json, dict
                    ), "The received data is not a valid JSON query."
                return request_json
            except AssertionError as e:
                raise HttpError(HttpResponseBadRequest(str(e)))
            except (TypeError, ValueError):
                raise HttpError(HttpResponseBadRequest("POST body sent invalid JSON."))

        elif content_type in [
            "application/x-www-form-urlencoded",
            "multipart/form-data",
        ]:
            return request.POST

        return {} 
Example #10
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 #11
Source File: __init__.py    From graphql-django-view with MIT License 5 votes vote down vote up
def get_graphql_params(request, data):
        query = request.GET.get('query') or data.get('query')
        variables = request.GET.get('variables') or data.get('variables')

        if variables and isinstance(variables, six.text_type):
            try:
                variables = json.loads(variables)
            except:
                raise HttpError(HttpResponseBadRequest('Variables are invalid JSON.'))

        operation_name = request.GET.get('operationName') or data.get('operationName')

        return query, variables, operation_name 
Example #12
Source File: home.py    From ldap-oauth2 with GNU General Public License v3.0 5 votes vote down vote up
def post(self, request):
        pp_form = ProfilePictureForm(request.POST, request.FILES)
        if pp_form.is_valid():
            profile_picture = pp_form.cleaned_data['profile_picture']
            userprofile = request.user.userprofile
            userprofile.profile_picture = profile_picture
            userprofile.save()
            response = {'url': userprofile.profile_picture.url}
            return HttpResponse(json.dumps(response))
        else:
            return HttpResponseBadRequest(json.dumps(pp_form.errors)) 
Example #13
Source File: mixins.py    From wagtail-orderable with MIT License 4 votes vote down vote up
def reorder_view(self, request, instance_pk):
        """
        Very simple view functionality for updating the `sort_order` values
        for objects after a row has been dragged to a new position.
        """
        self.fix_duplicate_positions()

        obj_to_move = get_object_or_404(self.model, pk=instance_pk)
        if not self.permission_helper.user_can_edit_obj(request.user, obj_to_move):
            raise PermissionDenied

        # determine the start position
        old_position = obj_to_move.sort_order or 0

        # determine the destination position
        after_position, after = self._get_position(request.GET.get('after'))
        before_position, before = self._get_position(request.GET.get('before'))
        if after:
            position = after_position or 0
            response = '"%s" moved after "%s"' % (obj_to_move, after)
        elif before:
            position = before_position or 0
            response = '"%s" moved before "%s"' % (obj_to_move, before)
        else:
            return HttpResponseBadRequest('"%s" not moved' % obj_to_move)

        # move the object from old_position to new_position
        if position < old_position:
            if position == after_position:
                position += 1
            self.model.objects.filter(
                sort_order__lt=old_position,
                sort_order__gte=position
            ).update(sort_order=F('sort_order') + 1)
        elif position > old_position:
            if position == before_position:
                position -= 1
            self.model.objects.filter(
                sort_order__gt=old_position,
                sort_order__lte=position
            ).update(sort_order=F('sort_order') - 1)

        obj_to_move.sort_order = position
        obj_to_move.save(update_fields=['sort_order'])
        return HttpResponse(response) 
Example #14
Source File: discoveries.py    From maas with GNU Affero General Public License v3.0 4 votes vote down vote up
def clear(self, request, **kwargs):
        """@description-title Delete all discovered neighbours
        @description Deletes all discovered neighbours and/or mDNS entries.

        Note: One of ``mdns``, ``neighbours``, or ``all`` parameters must be
        supplied.

        @param (boolean) "mdns" [required=false] Delete all mDNS entries.

        @param (boolean) "neighbours" [required=false] Delete all neighbour
        entries.

        @param (boolean) "all" [required=false] Delete all discovery data.

        @success (http-status-code) "server-success" 204
        """
        all = get_optional_param(
            request.POST, "all", default=False, validator=StringBool
        )
        mdns = get_optional_param(
            request.POST, "mdns", default=False, validator=StringBool
        )
        neighbours = get_optional_param(
            request.POST, "neighbours", default=False, validator=StringBool
        )

        if not request.user.has_perm(NodePermission.admin, Discovery):
            response = HttpResponseForbidden(
                content_type="text/plain",
                content="Must be an administrator to clear discovery entries.",
            )
            return response
        if True not in (mdns, neighbours, all):
            content = dedent(
                """\
                Bad request: could not determine what data to clear.
                Must specify mdns=True, neighbours=True, or all=True."""
            )
            response = HttpResponseBadRequest(
                content_type="text/plain", content=content
            )
            return response
        Discovery.objects.clear(
            user=request.user, all=all, mdns=mdns, neighbours=neighbours
        )
        return rc.DELETED 
Example #15
Source File: views.py    From django-datatables-view with MIT License 4 votes vote down vote up
def get(self, request, *args, **kwargs):

        # if not getattr(request, 'REQUEST', None):
        #     request.REQUEST = request.GET if request.method=='GET' else request.POST

        t0 = datetime.datetime.now()

        if not request.is_ajax():
            return HttpResponseBadRequest()

        try:
            query_dict = request.REQUEST
            params = self.read_parameters(query_dict)
        except ValueError:
            return HttpResponseBadRequest()

        if ENABLE_QUERYDICT_TRACING:
            trace(query_dict, prompt='query_dict')
            trace(params, prompt='params')

        # Prepare the queryset and apply the search and order filters
        qs = self.get_initial_queryset(request)
        if not DISABLE_QUERYSET_OPTIMIZATION and not self.disable_queryset_optimization:
            qs = self.optimize_queryset(qs)
        qs = self.prepare_queryset(params, qs)
        if ENABLE_QUERYSET_TRACING:
            prettyprint_queryset(qs)

        # Slice result
        paginator = Paginator(qs, params['length'] if params['length'] != -1 else qs.count())
        response_dict = self.get_response_dict(request, paginator, params['draw'], params['start'])
        response_dict['footer_message'] = self.footer_message(qs, params)

        # Prepare response
        response = HttpResponse(
            json.dumps(
                response_dict,
                cls=DjangoJSONEncoder
            ),
            content_type="application/json")

        # Trace elapsed time
        if ENABLE_QUERYSET_TRACING:
            td = datetime.datetime.now() - t0
            ms = (td.seconds * 1000) + (td.microseconds / 1000.0)
            trace('%d [ms]' % ms, prompt="Table rendering time")

        return response 
Example #16
Source File: views.py    From graphene-django with MIT License 4 votes vote down vote up
def execute_graphql_request(
        self, request, data, query, variables, operation_name, show_graphiql=False
    ):
        if not query:
            if show_graphiql:
                return None
            raise HttpError(HttpResponseBadRequest("Must provide query string."))

        try:
            backend = self.get_backend(request)
            document = backend.document_from_string(self.schema, query)
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True)

        if request.method.lower() == "get":
            operation_type = document.get_operation_type(operation_name)
            if operation_type and operation_type != "query":
                if show_graphiql:
                    return None

                raise HttpError(
                    HttpResponseNotAllowed(
                        ["POST"],
                        "Can only perform a {} operation from a POST request.".format(
                            operation_type
                        ),
                    )
                )

        try:
            extra_options = {}
            if self.executor:
                # We only include it optionally since
                # executor is not a valid argument in all backends
                extra_options["executor"] = self.executor

            return document.execute(
                root_value=self.get_root_value(request),
                variable_values=variables,
                operation_name=operation_name,
                context_value=self.get_context(request),
                middleware=self.get_middleware(request),
                **extra_options
            )
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True) 
Example #17
Source File: views.py    From pycon with MIT License 4 votes vote down vote up
def dispatch(self, request, *args, **kwargs):

        if request.method.lower() not in ("get", "post"):
            return HttpResponseNotAllowed(
                ["GET", "POST"], "GraphQL only supports GET and POST requests."
            )

        if "text/html" in request.META.get("HTTP_ACCEPT", ""):
            return render(
                request,
                "graphql/playground.html",
                {"REQUEST_PATH": request.get_full_path()},
            )

        data = json.loads(request.body)

        try:
            query = data["query"]
            variables = data.get("variables")
            operation_name = data.get("operationName")
        except KeyError:
            return HttpResponseBadRequest("No GraphQL query found in the request")

        context = {"request": request}

        result = graphql_sync(
            self.schema,
            query,
            variable_values=variables,
            context_value=context,
            operation_name=operation_name,
        )

        response_data = {"data": result.data}

        if result.errors:
            response_data["errors"] = [
                format_graphql_error(err) for err in result.errors
            ]
            self._capture_sentry_exceptions(result.errors)

        return JsonResponse(response_data, status=200)