本文整理匯總了Python中django.http.HttpResponseBadRequest方法的典型用法代碼示例。如果您正苦於以下問題:Python http.HttpResponseBadRequest方法的具體用法?Python http.HttpResponseBadRequest怎麽用?Python http.HttpResponseBadRequest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.http
的用法示例。
在下文中一共展示了http.HttpResponseBadRequest方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: form_detail
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def form_detail(request, slug, template="forms/form_detail.html"):
form = get_object_or_404(models.DocumentSetForm, slug=slug)
request_context = RequestContext(request)
args = (form, request_context, request.POST or None)
form_for_form = forms.DocumentSetFormForForm(*args)
if request.method == 'POST':
if not form_for_form.is_valid():
form_invalid.send(sender=request, form=form_for_form)
return HttpResponseBadRequest(json.dumps(form_for_form.errors), content_type='application/json')
else:
entry = form_for_form.save()
form_valid.send(sender=request, form=form_for_form, entry=entry, document_id=request.session['document_id_for_entry'])
return HttpResponse('')
return render_to_response(template, { 'form': form }, request_context)
示例2: random_suggestion
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def random_suggestion(cls, request: WSGIRequest) -> HttpResponse:
"""This method returns a random suggestion from the database.
Depending on the value of :param playlist:,
either a previously pushed playlist or song is returned."""
suggest_playlist = request.GET["playlist"] == "true"
if not suggest_playlist:
if ArchivedSong.objects.count() == 0:
return HttpResponseBadRequest("No songs to suggest from")
index = random.randint(0, ArchivedSong.objects.count() - 1)
song = ArchivedSong.objects.all()[index]
return JsonResponse({"suggestion": song.displayname(), "key": song.id})
# exclude radios from suggestions
remaining_playlists = (
ArchivedPlaylist.objects.all()
.exclude(list_id__startswith="RD")
.exclude(list_id__contains="&list=RD")
)
if remaining_playlists.count() == 0:
return HttpResponseBadRequest("No playlists to suggest from")
index = random.randint(0, remaining_playlists.count() - 1)
playlist = remaining_playlists.all()[index]
return JsonResponse({"suggestion": playlist.title, "key": playlist.id})
示例3: request_radio
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def request_radio(self, request: WSGIRequest) -> HttpResponse:
"""Endpoint to request radio for the current song."""
# only get ip on user requests
if self.base.settings.basic.logging_enabled:
request_ip, _ = ipware.get_client_ip(request)
if request_ip is None:
request_ip = ""
else:
request_ip = ""
try:
current_song = CurrentSong.objects.get()
except CurrentSong.DoesNotExist:
return HttpResponseBadRequest("Need a song to play the radio")
provider = SongProvider.create(self, external_url=current_song.external_url)
return provider.request_radio(request_ip)
示例4: post_song
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def post_song(self, request: WSGIRequest) -> HttpResponse:
"""This endpoint is part of the API and exempt from CSRF checks.
Shareberry uses this endpoint."""
# only get ip on user requests
if self.base.settings.basic.logging_enabled:
request_ip, _ = ipware.get_client_ip(request)
if request_ip is None:
request_ip = ""
else:
request_ip = ""
query = request.POST.get("query")
if not query:
return HttpResponseBadRequest("No query to share.")
# Set the requested platform to 'spotify'.
# It will automatically fall back to Youtube
# if Spotify is not enabled or a youtube link was requested.
successful, message, _ = self.do_request_music(
request_ip, query, None, False, "spotify"
)
if not successful:
return HttpResponseBadRequest(message)
return HttpResponse(message)
示例5: enable_streaming
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def enable_streaming(self, _request: WSGIRequest) -> HttpResponse:
"""Enable icecast streaming."""
icecast_exists = False
for line in subprocess.check_output(
"systemctl list-unit-files --full --all".split(), universal_newlines=True
).splitlines():
if "icecast2.service" in line:
icecast_exists = True
break
if not icecast_exists:
return HttpResponseBadRequest("Please install icecast2")
subprocess.call(["sudo", "/usr/local/sbin/raveberry/enable_streaming"])
config_file = os.path.join(settings.BASE_DIR, "setup/mopidy_icecast.conf")
self.update_mopidy_config(config_file)
return HttpResponse()
示例6: get_latest_version
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def get_latest_version(self, _request: WSGIRequest) -> HttpResponse:
"""Looks up the newest version number from PyPi and returns it."""
try:
subprocess.run(
"pip3 install raveberry==nonexistingversion".split(),
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
universal_newlines=True,
check=True,
)
except subprocess.CalledProcessError as e:
# parse the newest verson from pip output
for line in e.stderr.splitlines():
if "from versions" in line:
versions = [re.sub(r"[^0-9.]", "", token) for token in line.split()]
versions = [version for version in versions if version]
latest_version = versions[-1]
return HttpResponse(latest_version)
return HttpResponseBadRequest("Could not determine latest version.")
示例7: list_subdirectories
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def list_subdirectories(self, request: WSGIRequest) -> HttpResponse:
"""Returns a list of all subdirectories for the given path."""
path = request.GET.get("path")
if path is None:
return HttpResponseBadRequest("path was not supplied.")
basedir, subdirpart = os.path.split(path)
if path == "":
suggestions = ["/"]
elif os.path.isdir(basedir):
suggestions = [
os.path.join(basedir, subdir + "/")
for subdir in next(os.walk(basedir))[1]
if subdir.lower().startswith(subdirpart.lower())
]
suggestions.sort()
else:
suggestions = ["not a valid directory"]
if not suggestions:
suggestions = ["not a valid directory"]
return JsonResponse(suggestions, safe=False)
示例8: _set_extension_enabled
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def _set_extension_enabled(self, extension, enabled) -> HttpResponse:
if enabled:
if settings.DOCKER:
response = HttpResponse(
"Make sure you provided mopidy with correct credentials."
)
else:
extensions = self.base.settings.system.check_mopidy_extensions()
functional, message = extensions[extension]
if not functional:
return HttpResponseBadRequest(message)
response = HttpResponse(message)
else:
response = HttpResponse("Disabled extension")
Setting.objects.filter(key=f"{extension}_enabled").update(value=enabled)
setattr(self, f"{extension}_enabled", enabled)
return response
示例9: set_output_device
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def set_output_device(self, request: WSGIRequest) -> HttpResponse:
"""Sets the given device as default output device."""
device = request.POST.get("device")
if not device:
return HttpResponseBadRequest("No device selected")
try:
subprocess.run(
["pactl", "set-default-sink", device],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
env={"PULSE_SERVER": "127.0.0.1"},
check=True,
)
except subprocess.CalledProcessError as e:
return HttpResponseBadRequest(e.stderr)
# restart mopidy to apply audio device change
subprocess.call(["sudo", "/usr/local/sbin/raveberry/restart_mopidy"])
return HttpResponse(
f"Set default output. Restarting the current song might be necessary."
)
示例10: decide_invitation
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def decide_invitation(request, invite_id):
invite = get_object_or_404(TeamRequest, pk=invite_id)
team = invite.team
if team.owner_id is None or team.owner_id != request.user.id:
raise SuspiciousOperation(_('User is not the owner of the team'))
elif 'accept' in request.POST:
invite.team.members.add(invite.invitee)
invite.team.save()
notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
elif 'reject' in request.POST:
notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
else:
return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))
invite.delete()
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
示例11: join_team
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def join_team(request, team_id):
team = get_object_or_404(Team, pk=team_id)
if team.members.filter(id=request.user.id).exists():
raise SuspiciousOperation(_('User is already a member of the team'))
elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
team.members.add(request.user)
team.save()
TeamRequest.objects.filter(invitee=request.user, team=team).delete()
messages.success(request, _('Joined team {name}').format(name=team.name))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
return HttpResponseBadRequest(_('User already has a membership request with the team'))
else:
TeamRequest.objects.create(invitee=request.user, team=team)
if team.owner:
notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
示例12: GvizTableData
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def GvizTableData(request):
"""Returns a string formatted for consumption by a Google Viz table."""
#def throw_deadline():
# logging.info('MANUAL THROW!! DeadlineExceededError DeadlineExceededError')
# raise DeadlineExceededError
#t = Timer(15.0, throw_deadline)
test_set = None
category = request.GET.get('category')
if not category:
return http.HttpResponseBadRequest('Must pass category=something')
test_set = all_test_sets.GetTestSet(category)
if not test_set:
return http.HttpResponseBadRequest(
'No test set was found for category=%s' % category)
formatted_gviz_table_data = GetStats(request, test_set, 'gviz_table_data')
return http.HttpResponse(formatted_gviz_table_data)
示例13: bad_request
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def bad_request(request, template_name='400.html'):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
return http.HttpResponseBadRequest(template.render())
# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
示例14: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
def get(self, request, **kwargs):
token = kwargs.get('token')
try:
new_email = loads(token, max_age=self.timeout_seconds)
# 期限切れ
except SignatureExpired:
return HttpResponseBadRequest()
# tokenが間違っている
except BadSignature:
return HttpResponseBadRequest()
# tokenは問題なし
else:
User.objects.filter(email=new_email, is_active=False).delete()
request.user.email = new_email
request.user.save()
return super().get(request, **kwargs)
示例15: check_user
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseBadRequest [as 別名]
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")