Python rest_framework.response.Response() Examples

The following are 30 code examples for showing how to use rest_framework.response.Response(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.response , or try the search function .

Example 1
Project: sphinx-quant   Author: sphinx-quant   File: views.py    License: MIT License 6 votes vote down vote up
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 2
Project: django-puppy-store   Author: realpython   File: views.py    License: MIT License 6 votes vote down vote up
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 3
Project: django-puppy-store   Author: realpython   File: views.py    License: MIT License 6 votes vote down vote up
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 4
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 5
Project: controller   Author: deis   File: exceptions.py    License: MIT License 6 votes vote down vote up
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 6
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
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 7
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
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 8
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
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 9
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
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 10
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
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 11
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
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 12
Project: py2swagger   Author: Arello-Mobile   File: views.py    License: MIT License 6 votes vote down vote up
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 13
Project: py2swagger   Author: Arello-Mobile   File: views.py    License: MIT License 6 votes vote down vote up
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 14
Project: figures   Author: appsembler   File: views.py    License: MIT License 6 votes vote down vote up
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 15
Project: figures   Author: appsembler   File: views.py    License: MIT License 6 votes vote down vote up
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
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 17
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 19
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 20
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def rest_submission(request):
    if request.method == "POST":
        serializer = QMCDBSetSerializer(data=request.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)
    return HttpResponse(status=400) 
Example 21
Project: sphinx-quant   Author: sphinx-quant   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, format=None):
        result = add.delay(1, 2).get()
        return Response({"result": result}) 
Example 22
Project: sphinx-quant   Author: sphinx-quant   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, format=None):
        serializer = UserSerializer(request.user)
        return Response(serializer.data) 
Example 23
def test_bearer_authentication(self):
        @api_view(['GET'])
        @permission_classes([IsAuthenticated])
        @authentication_classes([BearerAuthentication])
        def my_view(request):
            return Response({})

        request = self.factory.get('/')
        response = my_view(request)
        self.assertEqual(response.status_code, 401)

        token = self._obtain_auth_token()
        request = self.factory.get('/', HTTP_AUTHORIZATION=f'Bearer {token}')
        response = my_view(request)
        self.assertEqual(response.status_code, 200) 
Example 24
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def orders(request, code=None, pk=None):
    """
    This is the orders API
    """
    from servo.api.serializers import OrderSerializer

    if request.method == 'POST':
        return create_order(request)

    if request.method == 'PUT':
        return error('Method not yet implemented')

    if request.GET.get('q'):
        results = Order.objects.filter(**request.GET)

    if pk:
        order = Order.objects.get(pk=pk)
        serializer = OrderSerializer(order, context={'request': request})
        return Response(serializer.data)

    if code:
        order = Order.objects.get(code=code)
        if order.status:
            order.status_description = order.status.status.description
        serializer = OrderSerializer(order, context={'request': request})
        return Response(serializer.data)

    orders = Order.objects.none()
    serializer = OrderSerializer(orders, many=True, context={'request': request})
    return Response(serializer.data) 
Example 25
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def order_status(request):
    from servo.api.serializers import OrderStatusSerializer
    code = request.GET.get('q')
    try:
        result = Order.objects.get(code=code)
        #serializer = OrderStatusSerializer(result)
        return Response(serializer.data)
    except Exception as e:
        return (error(e)) 
Example 26
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def notes(request, pk=None):
    if pk:
        note = Note.objects.get(pk=pk)
        serializer = NoteSerializer(note, context={'request': request})
        return Response(serializer.data) 
Example 27
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def order_items(request, pk):
    item = ServiceOrderItem.objects.get(pk=pk)
    serializer = ServiceOrderItemSerializer(item, context={'request': request})
    return Response(serializer.data) 
Example 28
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def customers(request, pk=None):
    customer = Customer.objects.get(pk=pk)
    serializer = CustomerSerializer(customer, context={'request': request})
    return Response(serializer.data) 
Example 29
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def devices(request, pk=None):
    device = Device.objects.get(pk=pk)
    serializer = DeviceSerializer(device, context={'request': request})
    return Response(serializer.data) 
Example 30
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def list(self, request, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, many=False)
        return Response(serializer.data)