Python django.http.HttpResponseBadRequest() Examples
The following are 30
code examples of django.http.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
, or try the search function
.
Example #1
Source File: views.py From anytask with MIT License | 6 votes |
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")
Example #2
Source File: library.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #3
Source File: suggestions.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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})
Example #4
Source File: platforms.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #5
Source File: system.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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.")
Example #6
Source File: views.py From civet with Apache License 2.0 | 6 votes |
def check_job_finished_post(request, build_key, client_name, job_id): data, response = check_post(request, ['seconds', 'complete']) if response: return response, None, None, None try: client = models.Client.objects.get(name=client_name, ip=get_client_ip(request)) except models.Client.DoesNotExist: return HttpResponseBadRequest('Invalid client'), None, None, None try: job = models.Job.objects.get(pk=job_id, client=client, event__build_user__build_key=build_key) except models.Job.DoesNotExist: return HttpResponseBadRequest('Invalid job/build_key'), None, None, None return None, data, client, job
Example #7
Source File: musiq.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #8
Source File: musiq.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #9
Source File: system.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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()
Example #10
Source File: sound.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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." )
Example #11
Source File: views.py From civet with Apache License 2.0 | 6 votes |
def process_event(user, json_data): ret = HttpResponse('OK') try: logger.info('Webhook called:\n{}'.format(json.dumps(json_data, indent=2))) object_kind = json_data.get("object_kind") if object_kind == 'merge_request': process_pull_request(user, json_data) elif object_kind == "push": if json_data.get("commits"): process_push(user, json_data) else: err_str = 'Unknown post to gitlab hook' logger.warning(err_str) ret = HttpResponseBadRequest(err_str) except Exception: err_str = "Invalid call to gitlab/webhook for user %s. Error: %s" % (user, traceback.format_exc()) logger.warning(err_str) ret = HttpResponseBadRequest(err_str) return ret
Example #12
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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,)))
Example #13
Source File: views.py From civet with Apache License 2.0 | 6 votes |
def process_event(user, json_data): ret = HttpResponse('OK') try: logger.info('Webhook called:\n{}'.format(json.dumps(json_data, indent=2))) if 'pull_request' in json_data: process_pull_request(user, json_data) elif 'commits' in json_data: process_push(user, json_data) elif 'release' in json_data: process_release(user, json_data) elif 'zen' in json_data: # this is a ping that gets called when first # installing a hook. Just log it and move on. logger.info('Got ping for user {}'.format(user.name)) else: err_str = 'Unknown post to github hook' logger.warning(err_str) ret = HttpResponseBadRequest(err_str) except Exception: err_str ="Invalid call to github/webhook for user %s. Error: %s" % (user, traceback.format_exc()) logger.warning(err_str) ret = HttpResponseBadRequest(err_str) return ret
Example #14
Source File: views.py From civet with Apache License 2.0 | 6 votes |
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 #15
Source File: util.py From browserscope with Apache License 2.0 | 6 votes |
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)
Example #16
Source File: defaults.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 %}.
Example #17
Source File: views.py From django-webmention with MIT License | 6 votes |
def receive(request): if "source" in request.POST and "target" in request.POST: source = request.POST.get("source") target = request.POST.get("target") webmention = None if not url_resolves(target): return HttpResponseBadRequest("Target URL did not resolve to a resource on the server") try: try: webmention = WebMentionResponse.objects.get(source=source, response_to=target) except WebMentionResponse.DoesNotExist: webmention = WebMentionResponse() response_body = fetch_and_validate_source(source, target) webmention.update(source, target, response_body) return HttpResponse("The webmention was successfully received", status=202) except (SourceFetchError, TargetNotFoundError) as e: webmention.invalidate() return HttpResponseBadRequest(str(e)) except Exception as e: return HttpResponseServerError(str(e)) else: return HttpResponseBadRequest("webmention source and/or target not in request")
Example #18
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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,)))
Example #19
Source File: views.py From django-register-sample with MIT License | 6 votes |
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)
Example #20
Source File: api.py From silverstrike with MIT License | 6 votes |
def get_balances(request, dstart, dend): try: dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d').date() dend = datetime.datetime.strptime(dend, '%Y-%m-%d').date() except ValueError: return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd')) balance = Split.objects.personal().exclude_transfers().filter(date__lt=dstart).aggregate( models.Sum('amount'))['amount__sum'] or 0 splits = Split.objects.personal().exclude_transfers().date_range(dstart, dend).order_by('date') data_points = [] labels = [] days = (dend - dstart).days if days > 50: step = days / 50 + 1 else: step = 1 for split in splits: while split.date > dstart: data_points.append(balance) labels.append(datetime.datetime.strftime(dstart, '%Y-%m-%d')) dstart += datetime.timedelta(days=step) balance += split.amount data_points.append(balance) labels.append(datetime.datetime.strftime(dend, '%Y-%m-%d')) return JsonResponse({'labels': labels, 'data': data_points})
Example #21
Source File: views.py From crowdata with MIT License | 6 votes |
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)
Example #22
Source File: search.py From DCRM with GNU Affero General Public License v3.0 | 5 votes |
def search_view(request): context = {} if request.POST: context.update(csrf(request)) context['request'] = request.POST['package'] context['package_list'] = Package.objects.filter(c_name__icontains=request.POST['package'])[:24] else: return HttpResponseBadRequest() return render(request, 'search.html', context)
Example #23
Source File: api.py From silverstrike with MIT License | 5 votes |
def category_spending(request, dstart, dend): try: dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d') dend = datetime.datetime.strptime(dend, '%Y-%m-%d') except ValueError: return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd')) res = Split.objects.expense().past().date_range(dstart, dend).order_by('category').values( 'category__name').annotate(spent=models.Sum('amount')) if res: res = [(e['category__name'] or 'No category', abs(e['spent'])) for e in res if e['spent']] categories, spent = zip(*res) else: categories, spent = [], [] return JsonResponse({'categories': categories, 'spent': spent})
Example #24
Source File: views.py From casepro with BSD 3-Clause "New" or "Revised" License | 5 votes |
def post(self, request, *args, **kwargs): org = request.org user = request.user action = kwargs["action"] message_ids = request.json["messages"] messages = org.incoming_messages.filter(org=org, backend_id__in=message_ids) lock_messages = [] if action == "lock": for message in messages: if message.get_lock(request.user): lock_messages.append(message.backend_id) if not lock_messages: for message in messages: message.user_lock(user) elif action == "unlock": for message in messages: message.user_unlock() else: # pragma: no cover return HttpResponseBadRequest("Invalid action: %s", action) return JsonResponse({"messages": lock_messages}, encoder=JSONEncoder)
Example #25
Source File: views.py From django_reddit with Apache License 2.0 | 5 votes |
def user_login(request): """ Pretty straighforward user authentication using password and username supplied in the POST request. """ if request.user.is_authenticated(): messages.warning(request, "You are already logged in.") return render(request, 'public/login.html') if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') if not username or not password: return HttpResponseBadRequest() user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) redirect_url = request.POST.get('next') or 'frontpage' return redirect(redirect_url) else: return render(request, 'public/login.html', {'login_error': "Account disabled"}) else: return render(request, 'public/login.html', {'login_error': "Wrong username or password."}) return render(request, 'public/login.html')
Example #26
Source File: test_comments.py From django_reddit with Apache License 2.0 | 5 votes |
def test_missing_type_or_id(self): self.c.login(**self.credentials) for key in ['parentType', 'parentId']: r = self.c.post(reverse('post_comment'), data={key: 'comment'}) self.assertIsInstance(r, HttpResponseBadRequest) r = self.c.post(reverse('post_comment'), data={'parentType': 'InvalidType', 'parentId': 1}) self.assertIsInstance(r, HttpResponseBadRequest)
Example #27
Source File: views.py From django-payfast with MIT License | 5 votes |
def notify_handler(request): """ Notify URL handler. On successful access 'payfast.signals.notify' signal is sent. Orders should be processed in signal handler. """ m_payment_id = request.POST.get('m_payment_id', None) order = get_object_or_404(PayFastOrder, m_payment_id=m_payment_id) form = NotifyForm(request, request.POST, instance=order) if not form.is_valid(): errors = form.plain_errors()[:255] order.request_ip = form.ip order.debug_info = errors order.trusted = False order.save() # XXX: Any possible data leakage here? return HttpResponseBadRequest( content_type='application/json', content=form.errors.as_json(), ) order = form.save() signals.notify.send(sender=notify_handler, order=order) return HttpResponse()
Example #28
Source File: api.py From silverstrike with MIT License | 5 votes |
def get_account_balance(request, account_id, dstart, dend): account = get_object_or_404(Account, pk=account_id) try: dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d').date() dend = datetime.datetime.strptime(dend, '%Y-%m-%d').date() except ValueError: return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd')) labels, data = zip(*account.get_data_points(dstart, dend)) return JsonResponse({'data': data, 'labels': labels})
Example #29
Source File: test_comments.py From django_reddit with Apache License 2.0 | 5 votes |
def test_invalid_or_wrong_parent_id(self): self.c.login(**self.credentials) test_data = { 'parentType': 'submission', 'parentId': 'invalid', 'commentContent': 'content' } r = self.c.post(reverse('post_comment'), data=test_data) self.assertIsInstance(r, HttpResponseBadRequest) test_data = { 'parentType': 'submission', 'parentId': 9999, 'commentContent': 'content' } r = self.c.post(reverse('post_comment'), data=test_data) self.assertIsInstance(r, HttpResponseBadRequest) test_data = { 'parentType': 'comment', 'parentId': 9999, 'commentContent': 'content' } r = self.c.post(reverse('post_comment'), data=test_data) self.assertIsInstance(r, HttpResponseBadRequest)
Example #30
Source File: views.py From civet with Apache License 2.0 | 5 votes |
def check_step_result_post(request, build_key, client_name, stepresult_id): data, response = check_post(request, ['step_num', 'output', 'time', 'complete', 'exit_status']) if response: return response, None, None, None try: step_result = (models.StepResult.objects .select_related('job', 'job__event', 'job__event__base__branch__repository', 'job__client', 'job__event__pull_request') .get(pk=stepresult_id)) except models.StepResult.DoesNotExist: return HttpResponseBadRequest('Invalid stepresult id'), None, None, None try: client = models.Client.objects.get(name=client_name, ip=get_client_ip(request)) except models.Client.DoesNotExist: return HttpResponseBadRequest('Invalid client'), None, None, None if client != step_result.job.client: return HttpResponseBadRequest('Same client that started is required'), None, None, None return None, data, step_result, client