本文整理汇总了Python中tastypie.serializers.Serializer类的典型用法代码示例。如果您正苦于以下问题:Python Serializer类的具体用法?Python Serializer怎么用?Python Serializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Serializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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')
)
示例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))
示例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>",
)
示例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)
示例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>',
)
示例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>",
)
示例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"}',
)
示例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)
示例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()
示例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
})
})
示例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),
})
示例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))
示例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()
示例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.')