本文整理汇总了Python中tastypie.serializers.Serializer.serialize方法的典型用法代码示例。如果您正苦于以下问题:Python Serializer.serialize方法的具体用法?Python Serializer.serialize怎么用?Python Serializer.serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tastypie.serializers.Serializer
的用法示例。
在下文中一共展示了Serializer.serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: top_level
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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: login
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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()
示例5: serialized
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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)
示例6: top_level
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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))
示例7: ProjectResourceTest
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
class ProjectResourceTest(TestCase):
fixtures = ['data.json']
def setUp(self):
super(ProjectResourceTest, self).setUp()
self.username = 'marcos'
self.password = 'test'
#self.user = User.objects.create_user(self.username, '[email protected]', self.password)
#self.api = slumber.API("http://localhost:5000/api/v1/", auth=(self.username, self.password))
self.post_data = {
'title': 'testTitle',
'description': 'testDescription',
'user' : '/api/v1/user/4ea9c4fdbb69337f8e000002/',
'tasks': []
}
self.serializer = Serializer()
def test_post_project(self):
format = self.serializer.content_types.get('json')
serialized_data = self.serializer.serialize(self.post_data, format='application/json')
self.assertEqual(Project.objects.count(), 1)
resp = self.client.post('/api/v1/project/', data = serialized_data, content_type='application/json')
self.assertEqual(resp.status_code, 201)
self.assertEqual(Project.objects.count(), 2)
def test_put_project(self):
format = self.serializer.content_types.get('json')
project_data = self.post_data
project_data['title'] = 'changedTitle'
serialized_data = self.serializer.serialize(project_data, format='application/json')
resp = self.client.put('/api/v1/project/4ea9c4fdbb69337f8e000001/', data = serialized_data, content_type='application/json')
self.assertEqual(resp.status_code, 204)
resp = self.client.get('/api/v1/project/')
self.assertEqual("changedTitle", self.serializer.deserialize(resp.content)['objects'][0]['title'])
def test_get_projects(self):
resp = self.client.get('/api/v1/project/')
self.assertEqual(resp.status_code, 200)
self.assertTrue(resp['Content-Type'].startswith('application/json'))
self.serializer.from_json(resp.content)
self.assertEqual(len(self.serializer.deserialize(resp.content)['objects']), 1)
assert True
"""def test_get_tasks(self):
示例8: is_key_valid
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
def is_key_valid(request, **kwargs):
user_key = request.GET.get('user_key')
try:
user_key = UserApiKey.objects.get(key=user_key)
key_valid = True
except UserApiKey.DoesNotExist:
key_valid = False
# self.log_throttled_access(request)
serializer = Serializer()
desired_format = determine_format(request, serializer)
serialized = serializer.serialize({'valid' : key_valid}, desired_format)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
示例9: view_response
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
def view_response(request, response, code):
from django.http import HttpResponse
from tastypie.serializers import Serializer
from tastypie.utils.mime import determine_format
serdes = Serializer(formats=["json", "xml"])
mimetype = determine_format(request, serdes)
response = serdes.serialize(response, mimetype)
del serdes
http_response = HttpResponse(response, mimetype=mimetype)
http_response.status_code = code
return http_response
示例10: sign_up
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
def sign_up(request):
"""
Create a new user including profile and send email with activation link.
"""
form = SignUpForm(request.POST)
serializer = Serializer()
format = determine_format(request, serializer,
default_format='application/json')
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
# Create new user (profile is automatically created)
user = User.objects.create(username=username, first_name=first_name,
last_name=last_name, email=email, is_active=False)
user.set_password(password)
user.save()
auth_profile = user.get_profile()
# Build the activation key
salt = sha.new(str(random())).hexdigest()[:5]
activation_key = sha.new(salt + user.username).hexdigest()
key_expires = datetime.datetime.now(pytz.utc) + datetime.timedelta(2)
# User is unactive until visiting activation link
auth_profile.activation_key = activation_key
auth_profile.key_expires = key_expires
activation_link = 'http://127.0.0.1:8000/auth/v1/activate/' + activation_key # TODO: replace with actual actication link (http://api.score-it.de/auth/v1/activate/)
auth_profile.save()
# TODO: Design better email
subject = _('Welcome to ScoreIt!')
message = _('To activate, please click the following link:\n' + activation_link)
sender = _('[email protected]')
recipients = [email]
send_mail(subject, message, sender, recipients)
user_resource = UserResource()
bundle = user_resource.build_bundle(obj=user, request=request)
user_resource.full_dehydrate(bundle)
return HttpResponse(user_resource.serialize(None, bundle, 'application/json'))
else:
return HttpResponseBadRequest(serializer.serialize(form.errors, format, {}))
示例11: top_level
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
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] = reverse("api_dispatch_list", kwargs={
'api_name': api_name,
'resource_name': name,
})
desired_format = "application/json"
serialized = serializer.serialize(available_resources, desired_format)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
示例12: NoteResourceTest
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
class NoteResourceTest(TestCase):
fixtures = ['data.json']
def setUp(self):
super(NoteResourceTest, self).setUp()
self.project_id = '4ea9c4fdbb69337f8e000001'
self.project = Project.objects.get(pk= self.project_id)
self.post_data = {
'title': 'testTitle',
'content': 'note content test',
}
self.serializer = Serializer()
self.user = User.objects.create_user("marcos2", '[email protected]', "test")
self.client.login(username = "marcos2", password = "test")
self.evernote_profile = EvernoteProfile()
self.user_profile = UserProfile(user = self.user, evernote_profile = self.evernote_profile)
self.user_profile.save()
def test_get_notes(self):
resp = self.client.get('/api/v1/project/{0}/notes/'.format(self.project_id))
self.assertEqual(resp.status_code, 200)
self.assertTrue(resp['Content-Type'].startswith('application/json'))
def test_post_note(self):
format = self.serializer.content_types.get('json')
serialized_data = self.serializer.serialize(self.post_data, format='application/json')
self.assertEqual(len(self.project.notes), 0)
resp = self.client.post('/api/v1/project/{0}/notes/'.format(self.project_id), data = serialized_data, content_type='application/json' )
self.project = Project.objects.get(pk= self.project_id)
self.assertEqual(resp.status_code, 201)
self.assertEqual(len(self.project.notes), 1)
def test_sync_evernote(self):
note = Note(title = 'test note sync', content = 'test content sync')
self.project.notes.append(note)
self.project.save()
createdNote = note.sync_note_evernote(self.user_profile.evernote_profile)
self.assertTrue(createdNote is not None)
self.assertTrue(createdNote.active)
def test_get_synced_notes(self):
Note.get_synced_notes(self.user_profile.evernote_profile)
self.assertTrue(False)
示例13: top_level
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
def top_level(self, request, api_name=None, **kwargs):
"""
A view that returns a serialized list of all resources registers
to the ``Api``. Useful for discovery.
"""
# TODO: Limit visibility of API to valid site IDs only.
# TODO: Potentially, we could only give pieces of the API out based on site ID.
serializer = Serializer()
available_resources = {}
if api_name is None:
api_name = self.api_name
for name in sorted(self._registry.keys()):
kw_bru = {
'api_name': api_name,
'resource_name': name,
}
kw_bru.update(self._registry[name].api_additional_parameters())
kw_bru.update(kwargs)
available_resources[name] = {
'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs=kw_bru),
'schema': self._build_reverse_url("api_get_schema", kwargs=kw_bru),
}
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: top_level
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
def top_level(self, request, api_name=None):
"""
Overriding top_level method to serialize only resources
that user has rights to use.
"""
serializer = Serializer()
available_resources = {}
if api_name is None:
api_name = self.api_name
for resource_name in sorted(self._registry.keys()):
available_resources[resource_name] = {
'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
'api_name': api_name,
'resource_name': resource_name,
}),
'schema': self._build_reverse_url("api_get_schema", kwargs={
'api_name': api_name,
'resource_name': resource_name,
}),
}
if not available_resources:
return HttpResponseForbidden()
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))
示例15: is_unique
# 需要导入模块: from tastypie.serializers import Serializer [as 别名]
# 或者: from tastypie.serializers.Serializer import serialize [as 别名]
def is_unique(request):
"""
Check if a username or email exists already
"""
data = {}
if 'user_name' in request.GET:
username = request.GET['user_name']
try:
User.objects.get(username=username)
unique = False
except User.DoesNotExist:
unique = True
except User.MultipleObjectsReturned:
unique = False
data['user_name'] = unique
if 'email' in request.GET:
email = request.GET['email']
try:
User.objects.get(email=email)
unique = False
except User.DoesNotExist:
unique = True
except User.MultipleObjectsReturned:
unique = False
data['email'] = unique
serializer = Serializer()
format = determine_format(request, serializer, default_format='application/json')
return HttpResponse(serializer.serialize(data, format, {}))