我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.http.HttpResponseBadRequest()。
def complete_login(request): auth = get_saml_auth(request) auth.process_response() errors = auth.get_errors() if errors: logger.error(auth.get_last_error_reason(), exc_info=True) return HttpResponseBadRequest( content='Error when processing SAML Response: {}'.format(', '.join(errors)) ) if auth.is_authenticated(): request.session['saml_attributes'] = auth.get_attributes() request.session['saml_nameid'] = auth.get_nameid() request.session['saml_session_index'] = auth.get_session_index() params = {'state': 'saml'} url = request.POST.get('RelayState', '/login') return HttpResponseRedirect(auth.redirect_to(url, parameters=params)) else: raise PermissionDenied()
def complete_logout(request): auth = get_saml_auth(request) url = auth.process_slo(delete_session_cb=lambda: request.session.flush()) errors = auth.get_errors() if errors: logger.error(auth.get_last_error_reason(), exc_info=True) return HttpResponseBadRequest( content='Error when processing SAML Logout Request: {}'.format(', '.join(errors)) ) params = {} if url: params['next'] = url return HttpResponseRedirect(auth.redirect_to('/logout', parameters=params))
def post(self, request): if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META: # Do not even attempt to process/store the event if there is # no paypal transmission id so we avoid overfilling the db. return HttpResponseBadRequest() trigger = WebhookEventTrigger.from_request(request) if trigger.exception: # An exception happened, return 500 return HttpResponseServerError() if not trigger.valid: # Webhook Event did not validate, return 400 return HttpResponseBadRequest() return HttpResponse(str(trigger.id))
def search(request): q = request.GET.get('q') if not q: return HttpResponseBadRequest("GET['q'] not set!") q = q.strip() try: document_ids = search_ids(q) except SearchError as e: return HttpResponseServerError(str(e)) documents = [get_document(id).parsed for id in document_ids] data = { 'status': 'ok', 'query': q, 'document_ids': document_ids, 'documents': documents, 'results': len(document_ids), } r = JsonResponse(data) r["Access-Control-Allow-Origin"] = '*' return r
def bad_request(request, exception, 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') # No exception content is passed to the template, to not disclose any sensitive information. 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 %}.
def task_tester(request): if request.method == 'POST': cache.set('marco', 'ping', 100) sample_task.delay('marco', 'polo', 10) return http.HttpResponse( 'Now make a GET request to this URL\n', status=201, ) else: if not cache.get('marco'): return http.HttpResponseBadRequest( 'Make a POST request to this URL first\n' ) for i in range(3): value = cache.get('marco') if value == 'polo': return http.HttpResponse('It works!\n') time.sleep(1) return http.HttpResponseServerError( 'Tried 4 times (4 seconds) and no luck :(\n' )
def ajax_required(f): """Check that the request is an AJAX request. Use it in your views: @ajax_required def my_view(request): .... Taken from: http://djangosnippets.org/snippets/771/ """ @wraps(f) def wrapper(request, *args, **kwargs): if not settings.DEBUG and not request.is_ajax(): return HttpResponseBadRequest("This must be an AJAX request.") return f(request, *args, **kwargs) return wrapper
def unpack_problem_json(request): data = json.loads(request.body.decode('utf-8')) if "name" not in data: return HttpResponseBadRequest("Need to include a reference to 'name' in the json object") if "courses" not in data: return HttpResponseBadRequest("Need to include a reference to 'courses' in the json object") if "tests" not in data: return HttpResponseBadRequest("Need to include a reference to 'tests' in the json object") if "solution_code" not in data: return HttpResponseBadRequest("Need to include a reference to 'solution_code' in the json object") courses = [] for c in data["courses"]: course = Course.objects.filter(id=c) if len(course) != 1: return HttpResponseBadRequest("No course exists with the ID " + str(c)) courses.append(course[0]) data["courses"] = courses return data
def get(self, request): try: start, end = get_start_end_paramters(request, default_days_back=1) except ValueError as e: return HttpResponseBadRequest(str(e)) combine = request.query_params.get('combine') sites = request.query_params.getlist('site') telescopes = request.query_params.getlist('telescope') try: telescope_availability = get_telescope_availability_per_day( start, end, sites=sites, telescopes=telescopes ) except ElasticSearchException: logger.warning('Error connecting to ElasticSearch. Is SBA reachable?') return Response('ConnectionError') if combine: telescope_availability = combine_telescope_availabilities_by_site_and_class(telescope_availability) str_telescope_availability = {str(k): v for k, v in telescope_availability.items()} return Response(str_telescope_availability)
def add_slack_btn(request): code = request.GET.get("code", "") if len(code) < 8: return HttpResponseBadRequest() result = requests.post("https://slack.com/api/oauth.access", { "client_id": settings.SLACK_CLIENT_ID, "client_secret": settings.SLACK_CLIENT_SECRET, "code": code }) doc = result.json() if doc.get("ok"): channel = Channel() channel.user = request.team.user channel.kind = "slack" channel.value = result.text channel.save() channel.assign_all_checks() messages.success(request, "The Slack integration has been added!") else: s = doc.get("error") messages.warning(request, "Error message from slack: %s" % s) return redirect("hc-channels")
def badge(request, username, signature, tag): if not check_signature(username, tag, signature): return HttpResponseBadRequest() status = "up" q = Check.objects.filter(user__username=username, tags__contains=tag) for check in q: if tag not in check.tags_list(): continue if status == "up" and check.in_grace_period(): status = "late" if check.get_status() == "down": status = "down" break svg = get_badge_svg(tag, status) return HttpResponse(svg, content_type="image/svg+xml")
def set_password(request, token): profile = request.user.profile if not check_password(token, profile.token): return HttpResponseBadRequest() if request.method == "POST": form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data["password"] request.user.set_password(password) request.user.save() profile.token = "" profile.save() # Setting a password logs the user out, so here we # log them back in. u = authenticate(username=request.user.email, password=password) auth_login(request, u) messages.success(request, "Your password has been set!") return redirect("hc-profile") return render(request, "accounts/set_password.html", {})
def updateData(request, table): data = request.data if table == "user": username = data['username'] if not User_data.objects.filter(username=username).exists(): return HttpResponseBadRequest('User record with username ' + username + ' does not exist') else: data.pop('username', None) user.objects.filter(username=username).update(**data) return HttpResponse('Put is successful') elif table == "program": pid = data['pid'] if not Program.objects.filter(pid=pid).exists(): return HttpResponseBadRequest('Program record with pid ' + str(pid) + ' does not exist') else: prog = Program.objects.get(pid=pid) data.pop('pid', None) Program.objects.filter(pid=pid).update(**data) return HttpResponse('Put is successful') else: return HttpResponseBadRequest('Put is not successful')
def deleteData(request, table): data = request.data if table == "user": username = data['username'] if not User_data.objects.filter(username=username).exists(): return HttpResponseBadRequest('User record with username ' + username + ' does not exist') else: user = User_data.objects.get(username=username) user.delete() elif table == "program": pid = data['pid'] if not Program.objects.filter(pid=pid).exists(): return HttpResponseBadRequest('Program record with pid ' + str(pid) + ' does not exist') else: prog = Program.objects.get(pid=pid) prog.delete() else: return HttpResponseBadRequest('Wrong table name') return HttpResponse('Delete is successful')
def parseRequest(request, table, id): data = request.data if table == 'user': username = data['username'] try: data = User_data.objects.filter(username=username).values() print(data) except User_data.DoesNotExist: return HttpResponse(status=404) return HttpResponse(data) elif table == "program": pid = data['pid'] try: data = Program.objects.filter(pid=id).values() except Program.DoesNotExist: return HttpResponse(status=404) return HttpResponse(data) else: return HttpResponseBadRequest('Wrong table name')
def image_to_pickle(request): if request.method == 'POST': try: params = json.loads(request.body) except: return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json") if not params.get('image_path') or not params.get('output_path'): return HttpResponseBadRequest(json.dumps({'error':'image_path and output_path required'}),content_type="application/json") try: data = get_data_from_image(params.get('image_path')) save_to_pickle(data,str(params.get('output_path'))+"/data.pickle") return HttpResponse(json.dumps({'success':True}),content_type="application/json") except Exception as e: return HttpResponseBadRequest(json.dumps({'error':str(e)}),content_type="application/json") else: raise Http404()
def run_algo(request): if request.method == 'POST': try: params = json.loads(request.body) except: return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json") if not params.get("image_pickle_file_path") or not params.get("algo") or not params.get('cluster_number') or not params.get('output_path'): return HttpResponseBadRequest(json.dumps({'error':'output_path ,image_pickle_file_path,cluster_number and algo manadatory,only .pickle file accepted, valid algo are '+str(default_params.algo_details.keys())}),content_type="application/json") pid_element = Results.objects.create(pid=None) params['id'] = pid_element.id params = json.dumps(params) command = "python segment_hsi.py '"+str(params)+"' &" proc = subprocess.Popen(command,shell=True) return HttpResponse(json.dumps({'success':True,'task_id':pid_element.id}),content_type="application/json") else: raise Http404()
def get_beta(request): if request.method == 'POST': try: params = json.loads(request.body) except: return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json") if not params.get("output_path") or not params.get("image_pickle_file_path"): return HttpResponseBadRequest(json.dumps({'error':'output_path and image_pickle_file_path manadatory'}),content_type="application/json") pid_element = Results.objects.create(pid=None) params['id'] = pid_element.id params = json.dumps(params) command = "python make_beta.py '"+str(params)+"' &" proc = subprocess.Popen(command,shell=True) return HttpResponse(json.dumps({'success':True,'task_id':pid_element.id}),content_type="application/json") else: raise Http404()
def get_weight(request): if request.method == 'POST': try: params = json.loads(request.body) except: return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json") if not params.get("output_path") or not params.get("image_pickle_file_path"): return HttpResponseBadRequest(json.dumps({'error':'output_path and image_pickle_file_path manadatory'}),content_type="application/json") pid_element = Results.objects.create(pid=None) params['id'] = pid_element.id params = json.dumps(params) command = "python make_weight.py '"+str(params)+"' &" proc = subprocess.Popen(command,shell=True) return HttpResponse(json.dumps({'success':True,'task_id':pid_element.id}),content_type="application/json") else: raise Http404()
def kill_task(request): if request.method == 'POST': try: params = json.loads(request.body) except: return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json") if not params.get("task_id"): return HttpResponseBadRequest(json.dumps({'error':'task_id manadatory'}),content_type="application/json") tasks = Results.objects.filter(id = params['task_id']) for task in tasks: try: parent = psutil.Process(task.pid) for child in parent.children(recursive=True): child.kill() parent.kill() except Exception as e: pass task.status_text = 'Killed' task.is_done = True task.save() return HttpResponse(json.dumps({'success':True}),content_type="application/json") else: raise Http404()
def get_task_status(request): if request.method == 'POST': try: params = json.loads(request.body) except: return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json") if not params.get("task_id"): return HttpResponseBadRequest(json.dumps({'error':'task_id manadatory'}),content_type="application/json") try: task = Results.objects.get(id=params['task_id']) data = {'task_id':task.id,'result_file_name':task.result_file_name,'error':task.error,'percentage_done':task.percentage_done, 'status_text':task.status_text,'is_done':task.is_done,'pid':task.pid} return HttpResponse(json.dumps(data),content_type="application/json") except Results.DoesNotExist as e: return HttpResponseBadRequest(json.dumps({'error':'Invalid task_id'}),content_type="application/json") else: raise Http404()
def get(self, request, **kwargs): """ Validate account from link sent by email. This endpoint tests if the token is in the database and if it's not expired, correspond to the correct user and if it's not consumed yet, then the user account will be validate after that. """ try: token = EmailValidationToken.objects.get(token=request.GET['token']) if not token.is_valid(request.GET['email']): raise ValueError('invalid token') token.consume() if not request.user.is_authenticated: self.login_user(token.user) messages.success(request, 'Email validated') return redirect('main:index') except (EmailValidationToken.DoesNotExist, ValueError) as e: print(e) return HttpResponseBadRequest('Something went wrong with your token, please try again')
def setUserStatus(request): """set user status to either active (is_active=True), banned(is_active=False), or admin(is_superuser=True)""" try: username = request.POST['username'] status = request.POST['status'] except KeyError: return HttpResponseBadRequest() try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404() if status == 'active': user.is_active = True user.is_superuser = False elif status == 'banned': user.is_active = False user.is_superuser = False elif status == 'admin': user.is_active = True user.is_superuser = True else: return HttpResponseBadRequest() user.save() return HttpResponse()
def set_info(request, tracker_id): """Set browser infos. :param request: :param tracker_id: :return: """ if not request.POST.get('infos'): return HttpResponseBadRequest() tracker = TrackerInfos.objects.filter( target_tracker_id=tracker_id, raw=None).order_by('created_at').last() if not tracker: return HttpResponseNotFound() tracker.raw = request.POST['infos'] tracker.save() return HttpResponse('')
def get(self, request, uuid=None): """Handles GET requests.""" user_profile = models.UserProfile.objects.get(user=request.user) try: tower = models.BTS.objects.get(uuid=uuid, network=user_profile.network) except models.BTS.DoesNotExist: return http.HttpResponseBadRequest() endaga_version = json.loads(tower.package_versions)['endaga_version'] context = { 'networks': get_objects_for_user(request.user, 'view_network', klass=models.Network), 'user_profile': user_profile, 'tower': tower, 'endaga_version': endaga_version, 'status': tower.get_status_display(), } # Render template. edit_template = template.loader.get_template( 'dashboard/tower_detail/deregister.html') html = edit_template.render(context, request) return http.HttpResponse(html)
def addmoney(request): if request.method == 'POST': amt = cents2mc(int(float(request.POST['amount']) * 100)) user_profile = UserProfile.objects.get(user=request.user) network = user_profile.network try: charge = network.authorize_card(amt, "credit", "Add Credit") network.add_credit(amt) network.capture_charge(charge.id) messages.add_message(request, messages.SUCCESS, "addmoney_stripe_success", extra_tags="billing_resp_code") return redirect("/dashboard/billing") except stripe.StripeError: logger.error("Failed to add money, stripe.CardError: %s", request) messages.add_message(request, messages.WARNING, "addmoney_stripe_error", extra_tags="billing_resp_code") return redirect("/dashboard/billing") else: return HttpResponseBadRequest()
def get(self, request, imsi=None): """Handles GET requests.""" user_profile = UserProfile.objects.get(user=request.user) network = user_profile.network try: subscriber = Subscriber.objects.get(imsi=imsi, network=network) except Subscriber.DoesNotExist: return HttpResponseBadRequest() initial_form_data = { 'imsi': subscriber.imsi } # Set the response context. context = { 'networks': get_objects_for_user(request.user, 'view_network', klass=Network), 'user_profile': user_profile, 'subscriber': subscriber, 'send_sms_form': dform.SubscriberSendSMSForm( initial=initial_form_data) } # Render template. template = get_template('dashboard/subscriber_detail/send_sms.html') html = template.render(context, request) return HttpResponse(html)
def delete(self, request, imsi=None): """Handle the deletion of Pending Credit Updates.""" user_profile = UserProfile.objects.get(user=request.user) network = user_profile.network request_data = QueryDict(request.body) if "pending_id" not in request_data: return HttpResponseBadRequest() pending_id = request_data['pending_id'] try: update = PendingCreditUpdate.objects.get(uuid=pending_id) except PendingCreditUpdate.DoesNotExist: return HttpResponseBadRequest() if update.subscriber.network != network: return HttpResponseBadRequest() update.delete() return HttpResponse()
def post(self, request, imsi=None): """Handles POST requests to change subscriber info.""" user_profile = UserProfile.objects.get(user=request.user) network = user_profile.network try: subscriber = Subscriber.objects.get(imsi=imsi, network=network) except Subscriber.DoesNotExist: return HttpResponseBadRequest() if (request.POST.get('name') and subscriber.name != request.POST.get('name')): subscriber.name = request.POST.get('name') subscriber.save() if request.POST.get('prevent_automatic_deactivation'): protected = ( request.POST.get('prevent_automatic_deactivation') == 'True') subscriber.prevent_automatic_deactivation = protected subscriber.save() messages.success(request, "Subscriber information updated.", extra_tags="alert alert-success") kwargs = { 'imsi': imsi } return redirect(urlresolvers.reverse('subscriber-edit', kwargs=kwargs))
def update_contact(request): """Handles a user changing their background contact info.""" if request.method == 'POST': if 'email' in request.POST: try: validate_email(request.POST['email']) request.user.email = request.POST['email'] except ValidationError: messages.error(request, "Invalid email address.", extra_tags="contact alert alert-danger") return redirect("/dashboard/profile") if 'first_name' in request.POST: request.user.first_name = request.POST['first_name'] if 'last_name' in request.POST: request.user.last_name = request.POST['last_name'] user_profile = UserProfile.objects.get(user=request.user) if 'timezone' in request.POST: user_profile.timezone = request.POST['timezone'] user_profile.save() request.user.save() messages.success(request, "Profile information updated.", extra_tags="contact alert alert-success") return redirect("/dashboard/profile") return HttpResponseBadRequest()
def update_notify_numbers(request): if request.method == 'POST': if 'notify_numbers' in request.POST: notify_numbers = request.POST['notify_numbers'].strip() if not notify_numbers == "": for current_number in notify_numbers.split(','): try: validate_phone(current_number.strip()) except ValidationError: messages.error(request, "Invalid phone number: '" + current_number + "'. Example of valid input is '+62000000, +52000000, +63000000'", extra_tags="alert alert-danger notify-numbers") return redirect("/dashboard/profile") network = UserProfile.objects.get(user=request.user).network network.notify_numbers = notify_numbers network.save() messages.success(request, "Notify numbers updated.", extra_tags="alert alert-success notify-numbers") return redirect("/dashboard/profile") return HttpResponseBadRequest()
def export_data(request, atype): if atype == "sheet": return excel.make_response_from_a_table( Customer, 'xls', file_name="sheet") elif atype == "custom": query_sets = Customer.objects.all() column_names = ['first_name', 'last_name', 'email', 'birthday'] return excel.make_response_from_query_sets( query_sets, column_names, 'xls', file_name="custom" ) else: return HttpResponseBadRequest( "Bad request. please put one of these " + "in your url suffix: sheet, book or custom")
def parameterval_png(request, pk): try: param = ParameterVal.objects.get(pk=pk) except ParameterVal.DoesNotExist: return HttpResponseNotFound() if not param.wf_module.public_authorized(): return HttpResponseForbidden() # is this actually in image? totes hardcoded for now if param.parameter_spec.id_name != 'chart': return HttpResponseBadRequest() # decode the base64 payload of the data URI into a png image_data = param.value.partition('base64,')[2] binary = base64.b64decode(image_data) return HttpResponse(binary, content_type='image/png')
def get(self, request, *args, **kwargs): try: answer = BalanceAnswer.objects.get(id=kwargs['pk']) except BalanceAnswer.DoesNotExist: return HttpResponseBadRequest(request) if hasattr(answer, 'match'): # we already created a match from this BalanceAnswer return super(MatchCreate, self).get(request, *args, **kwargs) # check that players from balance exist # (we don't allow CustomBalance results here) players = [p[0] for t in answer.teams for p in t['players']] players = Player.objects.filter(name__in=players) if len(players) < 10: return HttpResponseBadRequest(request) MatchManager.record_balance(answer, int(kwargs['winner'])) return super(MatchCreate, self).get(request, *args, **kwargs)
def dispatch(self,request,*args,**kwargs): ''' Check that a valid Invoice ID has been passed in session data, and that said invoice is marked as paid. ''' paymentSession = request.session.get(INVOICE_VALIDATION_STR, {}) self.invoiceID = paymentSession.get('invoiceID') self.amount = paymentSession.get('amount',0) self.success_url = paymentSession.get('success_url',reverse('registration')) # Check that Invoice matching passed ID exists try: i = Invoice.objects.get(id=self.invoiceID) except ObjectDoesNotExist: return HttpResponseBadRequest(_('Invalid invoice information passed.')) if i.unpaid or i.amountPaid != self.amount: return HttpResponseBadRequest(_('Passed invoice is not paid.')) return super(GiftCertificateCustomizeView,self).dispatch(request,*args,**kwargs)
def dispatch(self, request, *args, **kwargs): ids = request.GET.get('ids') ct = getIntFromGet(request,'ct') try: contentType = ContentType.objects.get(id=ct) self.objectClass = contentType.model_class() except (ValueError, ObjectDoesNotExist): return HttpResponseBadRequest(_('Invalid content type passed.')) # This view only deals with subclasses of Events (Public Events, Series, etc.) if not isinstance(self.objectClass(),Event): return HttpResponseBadRequest(_('Invalid content type passed.')) try: self.queryset = self.objectClass.objects.filter(id__in=[int(x) for x in ids.split(',')]) except ValueError: return HttpResponseBadRequest(_('Invalid ids passed')) return super(RepeatEventsView,self).dispatch(request,*args,**kwargs)
def get(self, request): """ Instagram will send a GET request to confirm our subscription url. They send a GET-parameter 'hub.challenge' and we have to reply with that value and only the value. """ log.debug("Instagram handling GET subscription") q_hub_mode = request.GET.get('hub.mode', False) q_hub_challenge = request.GET.get('hub.challenge', False) # TODO add a check when making a new subscription q_hub_verify_token = request.GET.get('hub.verify_token', False) log.debug("hub.mode: {}".format(q_hub_mode)) log.debug("hub.challenge: {}".format(q_hub_challenge)) log.debug("hub.verify_token: {}".format(q_hub_verify_token)) if q_hub_mode == 'subscribe' and q_hub_challenge is not False: log.debug("instagram hub verification successful") return HttpResponse(q_hub_challenge, content_type="text/plain") log.error("instagram hub verification failed") return HttpResponseBadRequest()
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME): """ 400 error handler. Templates: :template:`400.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_400_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html') # No exception content is passed to the template, to not disclose any sensitive information. 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 %}.
def get(self, request): if len(request.GET) > 1: formset = PageBlockQueryFormSet(request.GET) if not formset.is_valid(): return HttpResponseBadRequest('invalid query') pages = formset.get_query() else: formset = PageBlockQueryFormSet() pages = Page.objects.all() paginator, pages = paginate(request, pages.order_by('title')) for page in pages: page.can_choose = True return render(request, self.template_name, { 'base_url': replace_page_in_query(request.GET.urlencode(), None), 'formset': formset, 'pages': pages, })
def post(self, request): """ Handling GET method :param request: Request to View :return: HttpResponse with code 201 if user is created or HttpResponseBadRequest if request contain incorrect data """ verification_code = request.GET.get("code", "") invitation = AdviserInvitations.get_invitation(verification_code) user_registration_form = UserRegistrationForm(json.loads(request.body)) if not user_registration_form.is_valid(): return HttpResponseBadRequest("Invalid input data. Please edit and try again.") AdviserUser.create_user(user_registration_form, invitation) invitation.close_invitation() return HttpResponse(status=201)
def post(self, request): """Handling GET method :param request: Request to View :return: HttpResponse with code 201 if user is invited or HttpResponseBadRequest if request contain incorrect data """ invite_form = UserInvitationForm(json.loads(request.body)) if not invite_form.is_valid(): return HttpResponseBadRequest("Invalid input data. Please edit and try again.") if AdviserUser.objects.filter(user__email=invite_form.data[u'email']).exists(): return HttpResponseBadRequest("User with this e-mail is registered") if AdviserInvitations.objects.filter(email=invite_form.data[u'email']).exists(): return HttpResponseBadRequest("User with this e-mail is already invited") sender = EmailSender(invite_form.data[u'email']) sender.send_invite(invite_form.data[u'id_company']) return HttpResponse(status=201)
def post(self, request): """ Handling POST method :param json file with username and password :return: HttpResponse with superuser status and code 200 if user is invited or HttpResponseBadRequest if request contain incorrect data """ data = json.loads(request.body) login_form = LoginForm(data) if not login_form.is_valid(): return HttpResponseBadRequest('Invalid input data', status=401) username = data.get('username', None) password = data.get('password', None) user = auth.authenticate(username=username, password=password) if user: role = model_to_dict(User.objects.get(username=username)) response = HttpResponse('is_supeuser', status=200) response.set_cookie('role', value=role['is_superuser']) auth.login(request, user) return response else: return HttpResponseBadRequest("Incorrect email or password", status=401)
def put(self, request): """ Handling PUT method. Send project to chosen players. :param request: Request to View. :return: Http response with status code 400 if players weren`t added. Http response with status code 201 if project is sended. """ data = json.loads(request.body) if not data.get("players"): return HttpResponseBadRequest("Players are not added. Please, add some players.") project = AdviserProject.objects.get(id=data.get("project")["id"]) if (not request.user.is_superuser) and (project.id_company.id != request.user.adviseruser.id_company.id): return HttpResponseBadRequest("Permission denied") for player in data.get("players"): player = Player.get_by_id(player["id"]) player.project = project player.save() return HttpResponse(status=201)
def put(self, request): """ :param request: Request to View :return: change user info """ data = json.loads(request.body) user_form = UserForm(data['User']) if not user_form.is_valid(): return HttpResponseBadRequest('Invalid input data', status=400) adviser_user = AdviserUser.objects.get(id=data['AdviserUser']['id']) adviser_user.set_adviser_user(data['AdviserUser']) user = User.objects.get(id=data['User']['id']) user.last_name = data['User']['last_name'] user.first_name = data['User']['first_name'] user.save() return HttpResponse(status=201)
def check_superadmin(func): """ Decorator that check if authenticated user is a superadmin. :param func: function, that be wrapped :return: function """ def wrapper(self, request, *args, **kwargs): """ Wrapper, that checks authenticated user :param request: Django request :return: BadRequest when authenticated user is not a superadmin or function in other case """ if not request.user.is_superuser: return HttpResponseBadRequest("Permission denied") return func(self, request, *args, **kwargs) return wrapper
def put(self, request, company_id): """ Handling put method. :args request: Request to View. company_id: id of company to be updated. :return: HttpResponse with code 201 if company is updated or HttpResponseBadRequest if request contain incorrect data also if user is not superuser . """ if (not request.user.is_superuser) and (Company.get_company(company_id).administrator != request.user.adviseruser): return HttpResponseBadRequest("Permission denied") data = json.loads(request.body) if data.get("administrator"): data["administrator"] = AdviserUser.objects.get(id=data.get("administrator").get("id")) company = Company.get_company(data["id"]) company_form = CompanyForm(data, company) if not company_form.is_valid(): return HttpResponseBadRequest(str(company_form.errors)) company.set_company(data) return HttpResponse(status=201)
def sources(request): """ Content Source backend endpoint. Uses OpenEdx Course API v.1.0 :param request: :param course_id: :return: (JSON) blocks """ course_id = request.POST.get('course_id') if not course_id: return HttpResponseBadRequest(reason={"error": "`course_id` is a mandatory parameter."}) log.debug('course_ID{}'.format(course_id)) try: sources_list = get_available_blocks(course_id) except ObjectDoesNotExist as exc: return HttpResponseBadRequest(reason={"error": exc.message}) except HttpClientError as exc: return HttpResponseNotFound(reason={"error": exc.message}) return JsonResponse(data=sources_list, safe=False)
def display_certs(request): try: ct = int(request.GET["ct"]) ids = request.GET["ids"] except KeyError: return HttpResponseBadRequest() id_list = map(int, ids.split(",")) model = ContentType.objects.get(pk=ct).model_class() qs = model.objects.filter(pk__in=id_list) for client in qs: if not client.cert: client.create_cert() return render(request, "display_certs.html", {"objs": qs})