Python rest_framework.response.Response() Examples
The following are 30
code examples of rest_framework.response.Response().
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
rest_framework.response
, or try the search function
.
Example #1
Source File: views.py From django-puppy-store with MIT License | 7 votes |
def get_delete_update_puppy(request, pk): try: puppy = Puppy.objects.get(pk=pk) except Puppy.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # get details of a single puppy if request.method == 'GET': serializer = PuppySerializer(puppy) return Response(serializer.data) # update details of a single puppy if request.method == 'PUT': serializer = PuppySerializer(puppy, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # delete a single puppy if request.method == 'DELETE': puppy.delete() return Response(status=status.HTTP_204_NO_CONTENT)
Example #2
Source File: views.py From django-puppy-store with MIT License | 7 votes |
def get_post_puppies(request): # get all puppies if request.method == 'GET': puppies = Puppy.objects.all() serializer = PuppySerializer(puppies, many=True) return Response(serializer.data) # insert a new record for a puppy if request.method == 'POST': data = { 'name': request.data.get('name'), 'age': int(request.data.get('age')), 'breed': request.data.get('breed'), 'color': request.data.get('color') } serializer = PuppySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #3
Source File: api.py From Servo with BSD 2-Clause "Simplified" License | 7 votes |
def warranty(request): from servo.api.serializers import DeviceSerializer sn = request.GET.get('sn') if not sn: return error('Need query parameter for warranty lookup') try: GsxAccount.default(request.user) except Exception as e: return error('Cannot connect to GSX (check username and password)') try: result = Device.from_gsx(sn, cached=False) serializer = DeviceSerializer(result, context={'request': request}) return Response(serializer.data) except Exception as e: return error(e)
Example #4
Source File: views.py From controller with MIT License | 6 votes |
def users(self, request, *args, **kwargs): app = get_object_or_404(models.App, id=kwargs['id']) request.user = get_object_or_404(User, username=kwargs['username']) # check the user is authorized for this app if not permissions.is_app_user(request, app): raise PermissionDenied() data = {request.user.username: []} keys = models.Key.objects \ .filter(owner__username=kwargs['username']) \ .values('public', 'fingerprint') \ .order_by('created') if not keys: raise NotFound("No Keys match the given query.") for info in keys: data[request.user.username].append({ 'key': info['public'], 'fingerprint': info['fingerprint'] }) return Response(data, status=status.HTTP_200_OK)
Example #5
Source File: views.py From normandy with Mozilla Public License 2.0 | 6 votes |
def enable(self, request, pk=None): recipe = self.get_object() if recipe.approved_revision: try: recipe.approved_revision.enable(user=request.user) except EnabledState.NotActionable as e: return Response({"error": str(e)}, status=status.HTTP_409_CONFLICT) else: return Response( {"error": "Cannot enable a recipe that is not approved."}, status=status.HTTP_409_CONFLICT, ) recipe.latest_revision.refresh_from_db() return Response(RecipeSerializer(recipe).data)
Example #6
Source File: views.py From figures with MIT License | 6 votes |
def list(self, request): """ Returns site metrics data for current month TODO: NEXT Add query params to get data from previous months TODO: Add paginagation """ site = django.contrib.sites.shortcuts.get_current_site(self.request) course_keys = figures.sites.get_course_keys_for_site(site) date_for = datetime.utcnow().date() month_for = '{}/{}'.format(date_for.month, date_for.year) data = [] for course_key in course_keys: data.append(metrics.get_month_course_metrics(site=site, course_id=str(course_key), month_for=month_for)) return Response(data)
Example #7
Source File: views.py From normandy with Mozilla Public License 2.0 | 6 votes |
def reject(self, request, pk=None): approval_request = self.get_object() if not request.data.get("comment"): return Response( {"comment": "This field is required."}, status=status.HTTP_400_BAD_REQUEST ) try: approval_request.reject(approver=request.user, comment=request.data.get("comment")) except ApprovalRequest.NotActionable: return Response( {"error": "This approval request has already been approved or rejected."}, status=status.HTTP_400_BAD_REQUEST, ) except ApprovalRequest.CannotActOnOwnRequest: return Response( {"error": "You cannot reject your own approval request."}, status=status.HTTP_403_FORBIDDEN, ) return Response(ApprovalRequestSerializer(approval_request).data)
Example #8
Source File: views.py From py2swagger with MIT License | 6 votes |
def update(self, request, *args, **kwargs): """ --- responses: 201: description: 'Redefined response method' schema: allOf: - $ref: '#/definitions/TestModelSeriazlizer' - type: 'object' properties: new_custom_field2: type: string 200: description: 'Redefined response method' schema: allOf: - $ref: '#/definitions/TestModelSeriazlizer' - type: 'object' properties: new_custom_field3: type: string """ return Response(dict())
Example #9
Source File: views.py From sphinx-quant with MIT License | 6 votes |
def get(self, request, id, format=None): strategy_id = id if strategy_id: strategy_obj = Strategy.objects.get(id=strategy_id) code_text = strategy_obj.source_code.code_text backtest.delay( strategy_id=strategy_id, code_text=code_text, class_name="DoubleMaStrategy", vt_symbol="IF88.CFFEX", interval="1m", start_date=datetime(2016, 1, 1), end_date=datetime(2019, 1, 1), rate=3.0 / 10000, slippage=0.2, size=300, pricetick=0.2, capital=1_000_000, ) return Response({"status": "Process"}) return Response({"status": "Error"})
Example #10
Source File: views.py From py2swagger with MIT License | 6 votes |
def decorator_view(request): """ tags: - test parameters: - in: formData name: id description: Person ID type: integer required: true methods: - post responses: 200: description: Status [200, 400, 403, 405] schema: type: object properties: status: type: integer enum: [200, 400, 403, 405] """ return Response(dict())
Example #11
Source File: exceptions.py From controller with MIT License | 6 votes |
def custom_exception_handler(exc, context): # give more context on the error since DRF masks it as Not Found if isinstance(exc, Http404): set_rollback() return Response(str(exc), status=status.HTTP_404_NOT_FOUND) # Call REST framework's default exception handler after specific 404 handling, # to get the standard error response. response = exception_handler(exc, context) # No response means DRF couldn't handle it # Output a generic 500 in a JSON format if response is None: logging.exception('Uncaught Exception', exc_info=exc) set_rollback() return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # log a few different types of exception instead of using APIException if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)): logging.exception(exc.__cause__, exc_info=exc) return response
Example #12
Source File: views.py From controller with MIT License | 6 votes |
def destroy(self, request, **kwargs): calling_obj = self.get_object() target_obj = calling_obj if request.data.get('username'): # if you "accidentally" target yourself, that should be fine if calling_obj.username == request.data['username'] or calling_obj.is_superuser: target_obj = get_object_or_404(User, username=request.data['username']) else: raise PermissionDenied() # A user can not be removed without apps changing ownership first if len(models.App.objects.filter(owner=target_obj)) > 0: msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj)) # noqa raise AlreadyExists(msg) try: target_obj.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ProtectedError as e: raise AlreadyExists(e)
Example #13
Source File: views.py From controller with MIT License | 6 votes |
def passwd(self, request, **kwargs): if not request.data.get('new_password'): raise DeisException("new_password is a required field") caller_obj = self.get_object() target_obj = self.get_object() if request.data.get('username'): # if you "accidentally" target yourself, that should be fine if caller_obj.username == request.data['username'] or caller_obj.is_superuser: target_obj = get_object_or_404(User, username=request.data['username']) else: raise PermissionDenied() if not caller_obj.is_superuser: if not request.data.get('password'): raise DeisException("password is a required field") if not target_obj.check_password(request.data['password']): raise AuthenticationFailed('Current password does not match') target_obj.set_password(request.data['new_password']) target_obj.save() return Response({'status': 'password set'})
Example #14
Source File: views.py From controller with MIT License | 6 votes |
def regenerate(self, request, **kwargs): obj = self.get_object() if 'all' in request.data: for user in User.objects.all(): if not user.is_anonymous: token = Token.objects.get(user=user) token.delete() Token.objects.create(user=user) return Response("") if 'username' in request.data: obj = get_object_or_404(User, username=request.data['username']) self.check_object_permissions(self.request, obj) token = Token.objects.get(user=obj) token.delete() token = Token.objects.create(user=obj) return Response({'token': token.key})
Example #15
Source File: views.py From figures with MIT License | 6 votes |
def new_users(self, request): """ TODO: Rename the metrics module function to "new_users" to match this """ site = django.contrib.sites.shortcuts.get_current_site(self.request) date_for = datetime.utcnow().date() months_back = 6 new_users = metrics.get_monthly_history_metric( func=metrics.get_total_site_users_joined_for_time_period, site=site, date_for=date_for, months_back=months_back, ) data = dict(new_users=new_users) return Response(data)
Example #16
Source File: views.py From controller with MIT License | 6 votes |
def update(self, request, **kwargs): app = self.get_object() old_owner = app.owner if request.data.get('owner'): if self.request.user != app.owner and not self.request.user.is_superuser: raise PermissionDenied() new_owner = get_object_or_404(User, username=request.data['owner']) app.owner = new_owner # ensure all downstream objects that are owned by this user and are part of this app # is also updated for downstream_model in [models.AppSettings, models.Build, models.Config, models.Domain, models.Release, models.TLS]: downstream_model.objects.filter(owner=old_owner, app=app).update(owner=new_owner) app.save() return Response(status=status.HTTP_200_OK)
Example #17
Source File: views.py From normandy with Mozilla Public License 2.0 | 6 votes |
def add_user(self, request, pk=None): group = self.get_object() if not request.data.get("user_id"): return Response( {"user_id": "This field is required."}, status=status.HTTP_400_BAD_REQUEST ) try: user = User.objects.get(pk=request.data.get("user_id")) except User.DoesNotExist: return Response({"user_id": "Invalid user ID."}, status=status.HTTP_400_BAD_REQUEST) if request.user == user: return Response(status=status.HTTP_403_FORBIDDEN) user.groups.add(group) return Response(status=status.HTTP_204_NO_CONTENT)
Example #18
Source File: views.py From normandy with Mozilla Public License 2.0 | 6 votes |
def exception_handler(exc, context): """ Returns the response that should be used for any given exception. Adds support the DRF default to also handle django.core.exceptions.ValidationError Any unhandled exceptions may return `None`, which will cause a 500 error to be raised. """ response = original_exception_handler(exc, context) if response: return response elif isinstance(exc, DjangoValidationError): data = {"messages": exc.messages} set_rollback() return Response(data, status=status.HTTP_400_BAD_REQUEST) return None
Example #19
Source File: views.py From controller with MIT License | 6 votes |
def app(self, request, *args, **kwargs): app = get_object_or_404(models.App, id=kwargs['id']) perm_name = "api.use_app" usernames = [u.id for u in get_users_with_perms(app) if u.has_perm(perm_name, app)] data = {} result = models.Key.objects \ .filter(owner__in=usernames) \ .values('owner__username', 'public', 'fingerprint') \ .order_by('created') for info in result: user = info['owner__username'] if user not in data: data[user] = [] data[user].append({ 'key': info['public'], 'fingerprint': info['fingerprint'] }) return Response(data, status=status.HTTP_200_OK)
Example #20
Source File: views.py From figures with MIT License | 5 votes |
def active_users(self, request): site = django.contrib.sites.shortcuts.get_current_site(self.request) months_back = 6 active_users = metrics.get_site_mau_history_metrics(site=site, months_back=months_back) return Response(dict(active_users=active_users)) # # MAU metrics views #
Example #21
Source File: views.py From figures with MIT License | 5 votes |
def avg_progress(self, request, *args, **kwargs): site, course_id = self.site_course_helper(kwargs.get('pk', '')) data = dict(avg_progress=self.historic_data( request=request, site=site, course_id=course_id, func=metrics.get_course_average_progress_for_time_period)) return Response(data)
Example #22
Source File: views.py From figures with MIT License | 5 votes |
def list(self, request): """ Returns site metrics data for current month """ site = django.contrib.sites.shortcuts.get_current_site(self.request) data = metrics.get_current_month_site_metrics(site) return Response(data)
Example #23
Source File: views.py From figures with MIT License | 5 votes |
def avg_days_to_complete(self, request, *args, **kwargs): site, course_id = self.site_course_helper(kwargs.get('pk', '')) data = dict(avg_days_to_complete=self.historic_data( request=request, site=site, course_id=course_id, func=metrics.get_course_average_days_to_complete_for_time_period)) return Response(data)
Example #24
Source File: views.py From normandy with Mozilla Public License 2.0 | 5 votes |
def signed(self, request, pk=None): actions = self.filter_queryset(self.get_queryset()).exclude(signature=None) serializer = SignedActionSerializer(actions, many=True) return Response(serializer.data)
Example #25
Source File: views.py From figures with MIT License | 5 votes |
def course_completions(self, request): site = django.contrib.sites.shortcuts.get_current_site(self.request) date_for = datetime.utcnow().date() months_back = 6 course_completions = metrics.get_monthly_history_metric( func=metrics.get_total_course_completions_for_time_period, site=site, date_for=date_for, months_back=months_back, ) data = dict(course_completions=course_completions) return Response(data)
Example #26
Source File: views.py From figures with MIT License | 5 votes |
def num_learners_completed(self, request, *args, **kwargs): site, course_id = self.site_course_helper(kwargs.get('pk', '')) data = dict(num_learners_completed=self.historic_data( request=request, site=site, course_id=course_id, func=metrics.get_course_num_learners_completed_for_time_period)) return Response(data)
Example #27
Source File: views.py From figures with MIT License | 5 votes |
def list(self, request, *args, **kwargs): site = django.contrib.sites.shortcuts.get_current_site(self.request) course_overviews = figures.sites.get_courses_for_site(site) data = [] for co in course_overviews: data.append(retrieve_live_course_mau_data(site, co.id)) serializer = self.serializer_class(data, many=True) return Response(serializer.data)
Example #28
Source File: views.py From figures with MIT License | 5 votes |
def list(self, request, *args, **kwargs): """ We use list instead of retrieve because retrieve requires a resource identifier, like a PK """ site = django.contrib.sites.shortcuts.get_current_site(self.request) data = retrieve_live_site_mau_data(site) serializer = self.serializer_class(data) return Response(serializer.data)
Example #29
Source File: views.py From figures with MIT License | 5 votes |
def course_enrollments(self, request, *args, **kwargs): site, course_id = self.site_course_helper(kwargs.get('pk', '')) data = dict(course_enrollments=self.historic_data( request=request, site=site, course_id=course_id, func=metrics.get_course_enrolled_users_for_time_period)) return Response(data)
Example #30
Source File: views.py From figures with MIT License | 5 votes |
def course_enrollments(self, request): site = django.contrib.sites.shortcuts.get_current_site(self.request) date_for = datetime.utcnow().date() months_back = 6 course_enrollments = metrics.get_monthly_history_metric( func=metrics.get_total_enrollments_for_time_period, site=site, date_for=date_for, months_back=months_back, ) data = dict(course_enrollments=course_enrollments) return Response(data)