Python rest_framework.response() Examples

The following are 12 code examples of rest_framework.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 , or try the search function .
Example #1
Source File: rest.py    From patchew with MIT License 6 votes vote down vote up
def create(self, request, *args, **kwargs):
        m = MboxMessage(request.data["mbox"])
        projects = [p for p in Project.objects.all() if p.recognizes(m)]
        grps = request.user.groups.all()
        grps_name = [grp.name for grp in grps]
        if "importers" not in grps_name:
            projects = (p for p in projects if p.maintained_by(self.request.user))
        results = []
        for project in projects:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save(project=project)
            results.append(serializer.data)
        # Fake paginator response.  Note that there is no Location header.
        return Response(
            OrderedDict([("count", len(results)), ("results", results)]),
            status=status.HTTP_201_CREATED,
        )


# Results 
Example #2
Source File: rest.py    From patchew with MIT License 5 votes vote down vote up
def render(self, data, accepted_media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        response = renderer_context.get("response")
        if response and response.exception:
            return "%d %s" % (response.status_code, response.status_text.title())
        else:
            return data


# patchew-specific permission classes 
Example #3
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        response = super().form_valid(form)
        if hasattr(form, 'multiple_objects_created') and form.multiple_objects_created > 1:
            msg = '%d "%s" were created/updated successfully' % (
                form.multiple_objects_created,
                cap_words(self.object._meta.verbose_name_plural))
        else:
            msg = base_success_msg % (
                cap_words(self.object._meta.verbose_name),
                self.object.__str__(), self.success_message)
        messages.success(self.request, msg)
        return response 
Example #4
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def response(self, request, *args, **kwargs):
        try:
            data = self.get_json_data(request, *args, **kwargs)
        except Exception as e:
            return JsonResponse(str(e), encoder=ImprovedDjangoJSONEncoder, safe=False, status=400)
        return JsonResponse(data, encoder=ImprovedDjangoJSONEncoder, safe=False) 
Example #5
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        return self.response(request, *args, **kwargs) 
Example #6
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        return self.response(request, *args, **kwargs) 
Example #7
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def put(self, request, *args, **kwargs):
        return self.response(request, *args, **kwargs) 
Example #8
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def response(self, request, *args, **kwargs):
        try:
            data = self.process(request)
        except:
            data = self.failure()
        return JsonResponse(data, encoder=ImprovedDjangoJSONEncoder, safe=False) 
Example #9
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def finalize_response(self, request, response, *args, **kwargs):
        if self.response_unifier_serializer and \
                str(response.status_code)[0] not in ('4', '5') and \
                self.get_serializer_class() != self.response_unifier_serializer:
            try:
                if self.new_instance:
                    instance = self.new_instance
                else:
                    instance = self.get_object()
                response.data = self.response_unifier_serializer(instance, many=False).data
            except:
                pass
        return super().finalize_response(request, response, *args, **kwargs) 
Example #10
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        request.needs_action_logging = getattr(request, 'needs_action_logging', (request.method != 'GET'))
        response = super().dispatch(request, *args, **kwargs)
        if not request.needs_action_logging:
            return response

        if not request.user or not request.user.is_authenticated:
            return response

        user_action_name = self.get_action_name() or self.user_action_methods.get(request.method)\
                           or 'unknown'

        user_action_object_pk = user_action_object = None
        if 'pk' in self.kwargs:
            # need this to get rid of extra sql in elif
            user_action_object_pk = self.kwargs['pk']
            user_action_object_pk = None \
                if str(user_action_object_pk).lower() == 'null' else user_action_object_pk
        elif (self.lookup_url_kwarg or self.lookup_field) in self.kwargs:
            user_action_object = self.get_object()
        else:
            if request.method == 'GET':
                user_action_name = 'list'
        model = self.queryset.model
        content_type = ContentType.objects.get_for_model(model)
        user_action = Action(
            user=request.user,
            name=user_action_name,
            # content_type=content_type
        )
        if user_action_object_pk:
            user_action.object_pk = user_action_object_pk
        else:
            user_action.object = user_action_object
        # this should be added after all otherwise it throws error object has no content type
        user_action.content_type = content_type
        user_action.save()
        self.user_action = user_action
        return response 
Example #11
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def should_log(self, request, response):
        """
        Log only if enable logging via AppVar
        """
        # do not log FileResponse and other possible large responses
        if isinstance(response, StreamingHttpResponse):
            return False
        from apps.common.app_vars import TRACK_API
        return TRACK_API.val 
Example #12
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 4 votes vote down vote up
def list(self, request, *args, **kwargs):
        # 1. get full queryset
        queryset = self.get_queryset()
        # 2. filter and sort
        queryset = self.filter_queryset(queryset)
        # 2.1 export in xlsx if needed
        if request.GET.get('export_to') in ['csv', 'xlsx', 'pdf']:
            serializer = self.get_serializer(queryset, many=True)
            data = serializer.data

            if 'columns' in request.GET:
                columns = request.GET['columns'].split(',')
                data = [{k: v for k, v in i.items() if k in columns} for i in data]
            return self.export(data,
                               source_name=self.get_export_file_name() or
                                           queryset.model.__name__.lower(),
                               fmt=request.GET.get('export_to'))
        # 3. count total records !before queryset paginated
        # try:
        #     total_records = queryset.count()
        # except:
        #     total_records = len(queryset)
        # 4. get extra data !before queryset paginated
        extra_data = self.get_extra_data(queryset)
        # 5. paginate
        queryset = self.paginate_queryset(queryset)
        # 6. serialize
        serializer = self.get_serializer(queryset, many=True)
        data = serializer.data
        if isinstance(data, GeneratorType):
            data = list(data)
        # 6.1 filter "columns"
        if 'columns' in request.GET:
            columns = request.GET['columns'].split(',')
            data = [{k: v for k, v in i.items() if k in columns} for i in data]
        # 7. compose returned data
        show_total_records = json.loads(self.request.GET.get('total_records', 'false'))
        if show_total_records:
            # first try to use paginator to get total records
            total_records = getattr(queryset, 'total_records', None)
            if total_records is None:
                total_records = len(data)
            ret = {'data': data,
                   'total_records': total_records}
            if extra_data:
                ret.update(extra_data)
            return rest_framework.response.Response(ret)
        return rest_framework.response.Response(data)