python类JSONRenderer()的实例源码

views.py 文件源码 项目:af_quotes_api 作者: amanfojnr 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def quote_list(request, limit=263):
    """
    API endpoint that lists all quotes or a specific number of
    quotes

    limit --  the number of quotes to be returned
    """
    quotes = Quote.objects.all()[:int(limit)]
    serializer = QuoteSerializer(quotes, many=True)
    response = HttpResponse(JSONRenderer().render(serializer.data),
                            content_type='application/json')
    response["Access-Control-Allow-Origin"] = "*"
    return response
views.py 文件源码 项目:af_quotes_api 作者: amanfojnr 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def random_quote_detail(request):
    """
    API endpoint that generates a random quote
    """
    quote = Quote.objects.get(id=randrange(1, 264))
    serializer = QuoteSerializer(quote)
    response = HttpResponse(JSONRenderer().render(serializer.data),
                            content_type='application/json')
    response["Access-Control-Allow-Origin"] = "*"
    return response
renderers.py 文件源码 项目:boss 作者: jhuapl-boss 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def render(self, data, media_type=None, renderer_context=None):

        # Return data, squeezing time dimension as this only works with 3D data
        if not data["time_request"]:
            self.render_style = 'binary'
            data["data"].data = np.squeeze(data["data"].data, axis=(0,))
        else:
            # This appears to contain time data. Error out
            renderer_context["response"].status_code = 400
            renderer_context["accepted_media_type"] = 'application/json'
            self.media_type = 'application/json'
            self.format = 'json'
            err_msg = {"status": 400, "message": "The cutout service JPEG interface does not support 4D cutouts",
                       "code": 2005}
            jr = JSONRenderer()
            return jr.render(err_msg, 'application/json', renderer_context)

        if renderer_context['view'].bit_depth != 8:
            # This renderer only works on uint8 data
            renderer_context["response"].status_code = 400
            renderer_context["accepted_media_type"] = 'application/json'
            self.media_type = 'application/json'
            self.format = 'json'
            err_msg = {"status": 400, "message": "The cutout service JPEG interface only supports uint8 image data",
                       "code": 2001}
            jr = JSONRenderer()
            return jr.render(err_msg, 'application/json', renderer_context)

        # Reshape matrix
        d_shape = data["data"].data.shape
        data["data"].data = np.reshape(data["data"].data, (d_shape[0] * d_shape[1], d_shape[2]), order="C")

        # Save to Image
        jpeg_image = Image.fromarray(data["data"].data)
        img_file = io.BytesIO()
        jpeg_image.save(img_file, "JPEG", quality=85)

        # Send file
        img_file.seek(0)
        return img_file.read()
utils.py 文件源码 项目:django-billometer 作者: tcpcloud 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, data, **kwargs):
        content = JSONRenderer().render(
            data, renderer_context={'indent': 2, 'ensure_asci': False})
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)
react_polls.py 文件源码 项目:a4-meinberlin 作者: liqd 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def react_polls(context, question):
    question_serializer = serializers.QuestionSerializer(
        question,
        context={'request': context['request']}
    )

    return format_html(
        '<div data-mb-widget="polls" data-question="{question}"></div>',
        question=JSONRenderer().render(question_serializer.data)
    )
react_polls.py 文件源码 项目:a4-meinberlin 作者: liqd 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def react_poll_form(poll, reload_on_success=False):
    serializer = serializers.PollSerializer(poll)
    data_poll = JSONRenderer().render(serializer.data)
    reload_on_success = json.dumps(reload_on_success)

    return format_html(
        (
            '<div data-mb-widget="poll-management" data-module="{module}" '
            ' data-poll="{poll}"  data-reloadOnSuccess="{reload_on_success}">'
            '</div>'
        ),
        module=poll.module.pk,
        poll=data_poll,
        reload_on_success=reload_on_success,
    )
views.py 文件源码 项目:django-oauth2-test 作者: ONSdigital 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def post(self, request, *args, **kwargs):
        """
        Take the user object from the request and call the 'save' method on it to persist to the DB. If this succeeds
        then we can report a success.

        :param request:
        :param args:
        :param kwargs:
        :return: Serialised JSON Response Object to indicate the resource has been created
        """
        stdlogger.debug("Hitting HTTP POST account view")

        # Try and persist the user to the DB. Remember this could fail a data integrity check if some other system has
        # saved this user before we run this line of code!
        try:
            request.user.save()

        except (IntegrityError, InternalError, DataError, DatabaseError):
            # The chances of this happening are slim to none! And this line of code should never happen. So we really
            # need to tell the other system we are not capable of creating the resource.
            raise DatabaseFailureException

        context = {'account': request.user.email, 'created': 'success'}
        json_context = JSONRenderer().render(context)

        return Response(data=json_context, status=status.HTTP_201_CREATED,)
views.py 文件源码 项目:django-oauth2-test 作者: ONSdigital 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def put(self, request):
        """
        Take the user object from the request and updates user info if it exists in the DB. If the email (which is
        unique) is to be updated this will be in a new attribute within the PUT message called new_username.
        If this succeeds then we can report a success.

        :param request:
        :param args:
        :param kwargs:
        :return: Serialised JSON Response Object to indicate the resource has been created
        """

        stdlogger.debug("Hitting HTTP PUT account view")

        # Try and persist the user to the DB. Remember this could fail a data integrity check if some other system has
        # saved this user before we run this line of code!
        try:
            # Check to see if this PUT is changing the user ID. If it is, then keep the same user object with Primary
            # Key and change the email to the new one.
            if request.new_username:
                stdlogger.info("Admin is updating a user ID to a new value")
                request.user.email = request.new_username
            request.user.save()

        except (IntegrityError, InternalError, DataError, DatabaseError):
            # The chances of this happening are slim to none! And this line of code should never happen. So we really
            # need to tell the other system we are not capable of creating the resource.
            raise DatabaseFailureException

        context = {'account': request.user.email, 'updated': 'success'}
        json_context = JSONRenderer().render(context)

        return Response(data=json_context, status=status.HTTP_201_CREATED,)
views.py 文件源码 项目:ava-capture 作者: electronicarts 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)
views.py 文件源码 项目:AttendanceSystem 作者: HeerKirov 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def course_table(request):
    if not http_basic_auth(request):
        return HttpResponse('Unauthorized.', status=401)
    if request.method == 'GET':
        auth_number = request.user.authority.auth
        if has_auth(auth_number, AuthorityName.Student):
            courses = models.Course.objects.filter(as_student_set=request.user.as_student)
        elif has_auth(auth_number, AuthorityName.Teacher):
            courses = models.Course.objects.filter(teacher=request.user.as_teacher)
        else:
            return HttpResponse('Permission Denied.', status=403)
        params = request.GET  # ????
        if 'year' in params:
            courses = courses.filter(year=params['year'])
        if 'term' in params:
            courses = courses.filter(term=params['term'])
        ser = serializer.CourseTableSerializer(courses, many=True)
        course_table_json = json.loads(JSONRenderer().render(ser.data))
        # ??????????????????(?????????????/????)
        (now_year, now_month, now_day, now_hour, now_minute, now_second, _, _, _) = time.localtime(time.time())
        date_now = utils.date_to_str(now_year, now_month, now_day)
        schedules = models.SystemSchedule.objects.filter(begin__lte=date_now).filter(end__gte=date_now)
        if schedules:
            schedule = schedules.first()
            items = models.SystemScheduleItem.objects.filter(system_schedule=schedule).order_by('no')
            schedule_data = {
                'count': items.count(),
                'items': [
                    {
                        'begin': utils.time_to_str(item.begin.hour, item.begin.minute, item.begin.second),
                        'end': utils.time_to_str(item.end.hour, item.end.minute, item.end.second),
                        'no': item.no,
                    } for item in items
                ]
            }
        else:
            schedule_data = {
                'count': 0,
                'items': []
            }
        # ??????json???
        data = {
            'count': schedule_data['count'],
            'schedule_items': schedule_data['items'],
            'course_items': course_table_json,
        }
        return HttpResponse(json.dumps(data), status=200)
    else:
        return HttpResponse('Method Not Allowed', status=405)


问题


面经


文章

微信
公众号

扫码关注公众号