本文整理汇总了Python中django.http.response.HttpResponseBadRequest方法的典型用法代码示例。如果您正苦于以下问题:Python response.HttpResponseBadRequest方法的具体用法?Python response.HttpResponseBadRequest怎么用?Python response.HttpResponseBadRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.response
的用法示例。
在下文中一共展示了response.HttpResponseBadRequest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remove
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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()
示例2: reorder
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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()
示例3: get_graphql_params
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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
示例4: parse_body
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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 {}
示例5: control
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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)
示例6: prioritize
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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()
示例7: vote_up
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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()
示例8: sync_translations
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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'))
示例9: parse_body
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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 {}
示例10: execute_graphql_request
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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)
示例11: get_graphql_params
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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
示例12: post
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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))
示例13: dispatch
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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)
示例14: execute_graphql_request
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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)
示例15: get
# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponseBadRequest [as 别名]
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