• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python serializers.Serializer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tastypie.serializers.Serializer的典型用法代码示例。如果您正苦于以下问题:Python Serializer类的具体用法?Python Serializer怎么用?Python Serializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Serializer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: top_level

    def top_level(self, request, api_name=None):
        serializer = Serializer()
        available_resources = {}

        if api_name is None:
            api_name = self.api_name

        for name in sorted(self._registry.keys()):
            available_resources[name] = {
                'list_endpoint': self._build_reverse_url('api_dispatch_list', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
                'schema': self._build_reverse_url('api_get_schema', kwargs={
                    'api_name': api_name,
                    'resource_name': name,
                }),
            }

            if request.GET.get('include_schemas', False) is not False:
                available_resources[name]['schema_detailed'] = self._registry[name].build_schema()

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')
            
            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:BradZzz,项目名称:TastyBone,代码行数:35,代码来源:api.py


示例2: build_response

 def build_response(self):
     from tastypie.serializers import Serializer
     serializer = Serializer()
     return HttpResponse(
         content=serializer.serialize(self.response_data),
         content_type=build_content_type('application/json')
     )
开发者ID:WiserTogether,项目名称:django-tastypie,代码行数:7,代码来源:envelopes.py


示例3: top_level

 def top_level(self, request, api_name=None):
     """
     A view that returns a serialized list of all resources registers
     to the ``Api``. Useful for discovery.
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     desired_format = determine_format(request, serializer)
     serialized = serializer.serialize(available_resources, desired_format)
     return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:bmihelac,项目名称:django-tastypie,代码行数:26,代码来源:api.py


示例4: test_to_xml_single

 def test_to_xml_single(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     self.assertEqual(
         serializer.to_xml(resource),
         "<?xml version='1.0' encoding='utf-8'?>\n<object><updated>2010-03-30T20:05:00</updated><created>2010-03-30T20:05:00</created><title>First Post!</title><is_active type=\"boolean\">True</is_active><slug>first-post</slug><content>This is my very first post using my shiny new API. Pretty sweet, huh?</content><id>1</id><resource_uri></resource_uri></object>",
     )
开发者ID:robhudson,项目名称:django-tastypie,代码行数:7,代码来源:serializers.py


示例5: dbDecode

 def dbDecode(dataString):
     assert_arg_type(dataString, basestring)
     
     ## this logic is poor - I believe the best way is to define a standard set of 
     ## representation formats and use try..except clauses to parse the incoming string
     ## according to the defined formats (formats: text, json, xml)
     ## For now we treat it as a default of text
     
     ## use tastypie's serializer to do the testing 
     from tastypie.serializers import Serializer
     ## instantiate a serializer to test
     serdes = Serializer()
     
     dataobj = None
     val = None
     try:
         val = serdes.from_xml(dataString)
     except Exception:
         val = None
     
     if val is None:
         try:
             from django.utils import simplejson
             #val = serdes.from_json(dataString)
             val = simplejson.loads(dataString, encoding='utf-8')
         except Exception, ex:
             val = None
         
         if not isinstance(val, (dict, list)):
             val = str(dataString)
             dataobj = Data(val, data_format = Data.TEXT)
         else:
             dataobj = Data(val, data_format = Data.JSON)
开发者ID:asorici,项目名称:envived,代码行数:33,代码来源:objects.py


示例6: test_to_xml2

 def test_to_xml2(self):
     serializer = Serializer()
     sample_2 = self.get_sample2()
     self.assertEqual(
         serializer.to_xml(sample_2),
         '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<response><somelist type="list"><value>hello</value><value type="integer">1</value><value type="null"/></somelist><somehash type="hash"><pi type="float">3.14</pi><foo>bar</foo></somehash><false type="boolean">False</false><true type="boolean">True</true><somestring>hello</somestring></response>',
     )
开发者ID:robhudson,项目名称:django-tastypie,代码行数:7,代码来源:serializers.py


示例7: test_to_xml

 def test_to_xml(self):
     serializer = Serializer()
     sample_1 = self.get_sample1()
     self.assertEqual(
         serializer.to_xml(sample_1),
         "<?xml version='1.0' encoding='utf-8'?>\n<response><age type=\"integer\">27</age><name>Daniel</name><date_joined>2010-03-27</date_joined></response>",
     )
开发者ID:robhudson,项目名称:django-tastypie,代码行数:7,代码来源:serializers.py


示例8: test_to_json_decimal_list_dict

 def test_to_json_decimal_list_dict(self):
     serializer = Serializer()
     resource = self.another_obj_list[0]
     self.assertEqual(
         serializer.to_json(resource),
         '{"aliases": ["Mr. Smith", "John Doe"], "content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": "1", "is_active": true, "meta": {"threat": "high"}, "owed": "102.57", "resource_uri": "", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}',
     )
开发者ID:robhudson,项目名称:django-tastypie,代码行数:7,代码来源:serializers.py


示例9: serialized

 def serialized(self, request, api_name=None, desired_format=None):
     """
     Nabbed from top_level of the parent class
     Would be nice if this was abstracted as it's good for auto discovery
     to be rendered as json on initial page load
     """
     serializer = Serializer()
     available_resources = {}
     
     if api_name is None:
         api_name = self.api_name
         
     if desired_format is None:
         desired_format = determine_format(request, serializer)
     
     for name in sorted(self._registry.keys()):
         available_resources[name] = {
             'list_endpoint': self._build_reverse_url("api_dispatch_list", 
             kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
             'schema': self._build_reverse_url("api_get_schema", kwargs={
                 'api_name': api_name,
                 'resource_name': name,
             }),
         }
     
     return serializer.serialize(available_resources, desired_format)
开发者ID:bne,项目名称:hortee,代码行数:29,代码来源:utils.py


示例10: login

def login(request, **kwargs):
    # self.method_check(request, allowed=['post'])
    # self.is_authenticated(request)
    # self.throttle_check(request)

    developer_key = request.GET.get('developer_key')
    username = request.GET.get('username')
    password = request.GET.get('password')

    if not developer_key or not username or not password:
        return HttpUnauthorized()

    try:
        dev_key = DeveloperApiKey.objects.get(key=developer_key, approved=True)
    except DeveloperApiKey.DoesNotExist:
        return HttpUnauthorized()

    user = authenticate(username=username, password=password)

    if user:
        try:
            key = UserApiKey.objects.get(user=user, developer_key=dev_key)
        except  UserApiKey.DoesNotExist:
            key = UserApiKey(user=user, developer_key=dev_key)
            key.save()

        # self.log_throttled_access(request)
        serializer = Serializer()
        desired_format = determine_format(request, serializer)
        serialized = serializer.serialize({'key' : key.key}, desired_format)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
    else:
        return HttpUnauthorized()
开发者ID:MarcBehrens,项目名称:ScrumDo,代码行数:33,代码来源:views.py


示例11: index

def index(request):
    """
    Page shell for the client-side application.

    Bootstraps read-once data onto the page.
    """
    serializer = Serializer()
    cr = CategoryResource()

    categories = list(Category.objects.annotate(dataset_count=Count('datasets')))

    bundles = [cr.build_bundle(obj=c) for c in categories]
    categories_bootstrap = [cr.full_dehydrate(b) for b in bundles]

    uncategorized = Category(
        id=settings.PANDA_UNCATEGORIZED_ID,
        slug=settings.PANDA_UNCATEGORIZED_SLUG,
        name=settings.PANDA_UNCATEGORIZED_NAME)
    uncategorized.__dict__['dataset_count'] = Dataset.objects.filter(categories=None).count() 
    uncategorized_bundle = cr.full_dehydrate(cr.build_bundle(obj=uncategorized))

    categories_bootstrap.append(uncategorized_bundle)

    return render_to_response('index.html', {
        'settings': settings,
        'demo_mode': int(config_value('MISC', 'DEMO_MODE')),
        'bootstrap_data': serializer.to_json({
            'categories': categories_bootstrap
        })
    })
开发者ID:eads,项目名称:panda,代码行数:30,代码来源:views.py


示例12: index

def index(request):
    """
    Page shell for the client-side application.

    Bootstraps read-once data onto the page.
    """
    serializer = Serializer()
    cr = CategoryResource()

    categories = list(Category.objects.annotate(dataset_count=Count('datasets')))

    bundles = [cr.build_bundle(obj=c) for c in categories]
    categories_bootstrap = [cr.full_dehydrate(b) for b in bundles]

    uncategorized = Category(
        id=settings.PANDA_UNCATEGORIZED_ID,
        slug=settings.PANDA_UNCATEGORIZED_SLUG,
        name=settings.PANDA_UNCATEGORIZED_NAME)
    uncategorized.__dict__['dataset_count'] = Dataset.objects.filter(categories=None).count() 
    uncategorized_bundle = cr.full_dehydrate(cr.build_bundle(obj=uncategorized))

    categories_bootstrap.append(uncategorized_bundle)

    return render_to_response('index.html', {
        'settings': settings,
        'max_upload_size': int(config_value('MISC', 'MAX_UPLOAD_SIZE')),
        'email_enabled': int(config_value('EMAIL', 'EMAIL_ENABLED')),
        'demo_mode_enabled': int(config_value('MISC', 'DEMO_MODE_ENABLED')),
        'bootstrap_data': serializer.to_json({
            'categories': categories_bootstrap
        }),
        'moment_lang_code': settings.MOMENT_LANGUAGE_MAPPING.get(settings.LANGUAGE_CODE, None),
    })
开发者ID:Web5design,项目名称:panda,代码行数:33,代码来源:views.py


示例13: top_level

    def top_level(self, request, api_name=None):
        """
        A view that returns a serialized list of all resources registers
        to the ``Api``. Useful for discovery.
        """
        serializer = Serializer()

        if api_name is None:
            api_name = self.api_name

        available_resources = dict((name, {
            'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
            'schema': self._build_reverse_url("api_get_schema", kwargs={
                'api_name': api_name,
                'resource_name': name,
            }),
        }) for name in self._registry.iterkeys())

        desired_format = determine_format(request, serializer)
        options = {}

        if 'text/javascript' in desired_format:
            callback = request.GET.get('callback', 'callback')

            if not is_valid_jsonp_callback_value(callback):
                raise BadRequest('JSONP callback name is invalid.')

            options['callback'] = callback

        serialized = serializer.serialize(available_resources, desired_format, options)
        return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:georgemarshall,项目名称:django-tastypie,代码行数:34,代码来源:api.py


示例14: obj_update

 def obj_update(self, bundle, skip_errors=False, **kwargs):
     from tastypie.serializers import Serializer
     from models import ProgramFeature
     
     serdes = Serializer()
     deserialized = None
     
     try:
         deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
     except Exception:
         deserialized = None
     
     if deserialized is None:
         return ImmediateHttpResponse(response = http.HttpBadRequest('Empty update data'))
     
     time_difference = datetime.strptime(deserialized['new_end_time'], "%Y-%m-%d %H:%M:%S") - datetime.strptime(deserialized['old_end_time'], "%Y-%m-%d %H:%M:%S")
     
     Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(startTime=F('startTime') + time_difference)
     Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(endTime=F('endTime') + time_difference)
     
     later_presentations = Presentation.objects.filter(startTime__gte=deserialized['old_end_time'])
     
     changed_presentation = Presentation.objects.get(startTime=deserialized['old_start_time'])
     changed_presentation.startTime = deserialized['new_start_time']
     changed_presentation.endTime = deserialized['new_end_time']
     changed_presentation.save()
开发者ID:asorici,项目名称:envived,代码行数:26,代码来源:api.py


示例15: send_invitation

def send_invitation(request):
    """
        Send an invitation to another person via email. NOT TESTED YET
    """
    if request.user.is_authenticated() and request.user.is_active:
        if 'email' in request.POST:
            email = request.POST['email']
        else:
            return HttpResponseBadRequest('Mandatory email parameter not provided.')

        if 'message' in request.POST:
            message = request.POST['message']
        else:
            message = 'Tritt score.it bei und sehe deine Handballergebnisse online!'

        profile = None
        if 'profile' in request.POST:
            serializer = Serializer()
            profile = serializer.deserialize(request.POST['profile'])

        subject = '{0} {1} lädt dich zu Score.it ein!'.format(request.user.first_name, request.user.last_name)

        if profile:
            profile_link = 'http://score-it.de/?a=invite&p={0}'.format(profile.id)
            body = '{0} {1} hat ein Spielerprofil bei Score.it für dich erstellt. Melde dich jetzt bei Score.it an, um deine Handballergebnisse online abzurufen! Zum anmelden, klicke einfach folgenden Link: {3}'.format(request.user.first_name, request.user.last_name, profile_link)
        else:
            body = '{0} {1} hat dir eine Einladung zu der Sportplatform Score.it geschickt:<br>{2}Um dich anzumelden, besuche einfach http://score-it.de/!'.format(request.user.first_name, request.user.last_name, message)

        sender = '[email protected]'
        recipients = [email]
        send_mail(subject, body, sender, recipients)
        return HttpResponse('')
    else:
        return HttpUnauthorized('Authentication through active user required.')
开发者ID:Engaginglab,项目名称:scoreit-handball,代码行数:34,代码来源:api.py


示例16: tastypie_resource_serialize

 def tastypie_resource_serialize(data):
     data_resource = get_resource_class(type(data))
     bundle = data_resource.build_bundle(obj=data, request=None)
     bundle.request.path = "/"
     serialized = Serializer().serialize(data_resource.full_dehydrate(bundle).data)
     serialized = serialized.replace("'", '\\"')
     return serialized
开发者ID:ibobriakov,项目名称:solidrock,代码行数:7,代码来源:serialize.py


示例17: test_to_json_single

 def test_to_json_single(self):
     serializer = Serializer()
     resource = self.obj_list[0]
     self.assertEqual(
         serializer.to_json(resource),
         '{"content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": "1", "is_active": true, "resource_uri": "", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}',
     )
开发者ID:robhudson,项目名称:django-tastypie,代码行数:7,代码来源:serializers.py


示例18: obj_update

 def obj_update(self, bundle, skip_errors=False, **kwargs):
     """
     Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned
     as acceptable exceptions which get transformed into a CREATE operation.
     We don't want such a behavior. So we catch does exceptions and throw an BadRequest message
     """ 
     from tastypie.serializers import Serializer
        
     try:
         serdes = Serializer()
         deserialized = None
         try:
             deserialized = serdes.deserialize(bundle.request.raw_post_data, 
                                 format=bundle.request.META.get('CONTENT_TYPE', 'application/json'))
         except Exception:
             deserialized = None
         del serdes
                 
         if deserialized is None:
             return ImmediateHttpResponse(response = http.HttpBadRequest())
         
         if 'unregister_c2dm' in deserialized and deserialized['unregister_c2dm'] == True:
             bundle.data['c2dm_id'] = None
         
         updated_bundle = super(UserResource, self).obj_update(bundle, skip_errors=skip_errors, **kwargs)
         return updated_bundle
     except (NotFound, MultipleObjectsReturned):
         raise ImmediateHttpResponse(response = http.HttpBadRequest())
开发者ID:asorici,项目名称:envived,代码行数:28,代码来源:api.py


示例19: test_to_plist

    def test_to_plist(self):
        if not biplist:
            return

        serializer = Serializer()

        sample_1 = self.get_sample1()
        self.assertTrue(serializer.to_plist(sample_1).startswith(b'bplist00bybiplist1.0'))
开发者ID:5783354,项目名称:django-tastypie,代码行数:8,代码来源:serializers.py


示例20: test_to_plist

    def test_to_plist(self):
        if not biplist:
            return

        serializer = Serializer()

        sample_1 = self.get_sample1()
        self.assertEqual(serializer.to_plist(sample_1), 'bplist00bybiplist1.0\x00\xd4\x01\x02\x03\x04\x05\x06\x07\x08WsnowmanSageTname[date_joineda&\x03\x10\x1bf\x00D\x00a\x00n\x00i\x00e\x00lZ2010-03-27\x15\x1e&*/;>@M\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00X')
开发者ID:UCSD-TIES,项目名称:django-tastypie,代码行数:8,代码来源:serializers.py



注:本文中的tastypie.serializers.Serializer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python test.TestApiClient类代码示例发布时间:2022-05-27
下一篇:
Python resources.ModelResource类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap