本文整理匯總了Python中rest_framework.serializers.Serializer方法的典型用法代碼示例。如果您正苦於以下問題:Python serializers.Serializer方法的具體用法?Python serializers.Serializer怎麽用?Python serializers.Serializer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類rest_framework.serializers
的用法示例。
在下文中一共展示了serializers.Serializer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: handle_invalid_fields
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def handle_invalid_fields(this, data):
"""Validate incoming data.
The primary validation being done is ensuring the incoming data only
contains known fields.
Args:
this (Object): Serializer object
data (Dict): data to be validated
Returns:
(Dict): Validated data
Raises:
(ValidationError): if field inputs are invalid
"""
unknown_keys = None
if hasattr(this, "initial_data"):
unknown_keys = set(this.initial_data.keys()) - set(this.fields.keys())
if unknown_keys:
error = {}
for unknown_key in unknown_keys:
error[unknown_key] = _("Unsupported parameter or invalid value")
raise serializers.ValidationError(error)
return data
示例2: get_serializer_class
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def get_serializer_class(self, **kwargs) -> Type[Serializer]:
"""
Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
(Eg. admins get full serialization, others get basic serialization)
"""
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method." % self.__class__.__name__
)
return self.serializer_class
示例3: save
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def save(self, *args, **kwargs):
"""Serializer save that address prefetch issues."""
update = getattr(self, 'instance', None) is not None
instance = super(
WithDynamicSerializerMixin,
self
).save(
*args,
**kwargs
)
view = self._context.get('view')
if view and update:
if int(DRF_VERSION[0]) <= 3 and int(DRF_VERSION[1]) < 5:
# Reload the object on update
# to get around prefetch cache issues
# Fixed in DRF in 3.5.0
instance = self.instance = view.get_object()
return instance
示例4: test_char_field_error_content
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_char_field_error_content(self):
# Too long string
self.data_set['title'] = 'Too Long Title For Defined Serializer'
s = run_is_valid(SnippetSerializer, data=self.data_set)
code = settings.FRIENDLY_FIELD_ERRORS['CharField']['max_length']
self.assertEqual(s.errors['errors'][0]['code'], code)
self.assertEqual(s.errors['errors'][0]['field'], 'title')
# Empty string
self.data_set['title'] = ''
s = run_is_valid(SnippetSerializer, data=self.data_set)
code = settings.FRIENDLY_FIELD_ERRORS['CharField']['blank']
self.assertEqual(s.errors['errors'][0]['code'], code)
self.assertEqual(s.errors['errors'][0]['field'], 'title')
# No data provided
self.data_set.pop('title')
s = run_is_valid(SnippetSerializer, data=self.data_set)
code = settings.FRIENDLY_FIELD_ERRORS['CharField']['required']
self.assertEqual(s.errors['errors'][0]['code'], code)
self.assertEqual(s.errors['errors'][0]['field'], 'title')
示例5: test_pagination_multiple_datatypes
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_pagination_multiple_datatypes(self):
req = self._get_request('/foo', {'limit': 10, 'offset': 20})
qs1 = [{'id': i} for i in range(25)]
qs2 = [{'name': i} for i in range(25)]
class FakeSerializer1(serializers.Serializer):
id = serializers.IntegerField()
class FakeSerializer2(serializers.Serializer):
name = serializers.IntegerField()
resp = paginate_results(
req, (qs1, FakeSerializer1), (qs2, FakeSerializer2))
assert resp == {
'count': 50,
'next': 'http://nxt',
'previous': 'http://prv',
'results': (
[{'id': 20+i} for i in range(5)] +
[{'name': i} for i in range(5)]
)
}
示例6: __init__
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def __init__(self, data=None, code=errors.SUCCESS, message=None,
template_name=None, headers=None, exception=False, content_type=None):
super(Response, self).__init__(None, status=HTTP_200_OK)
if isinstance(data, Serializer):
msg = (
'You passed a Serializer instance as data, but '
'probably meant to pass serialized `.data` or '
'`.error`. representation.'
)
raise AssertionError(msg)
self.data = {'code': code,
'message': message if message else errors.MESSAGES.get(code, errors.UNKNOWN_ERROR),
'data': data}
self.template_name = template_name
self.exception = exception
self.content_type = content_type
if headers:
for name, value in six.iteritems(headers):
self[name] = value
示例7: get_paginator_serializer
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def get_paginator_serializer(self, view, child_serializer_class):
class BaseFakeListSerializer(serializers.Serializer):
results = child_serializer_class(many=True)
class FakePrevNextListSerializer(BaseFakeListSerializer):
next = URLField()
previous = URLField()
# Validate if the view has a pagination_class
if not (hasattr(view, 'pagination_class')) or view.pagination_class is None:
return BaseFakeListSerializer
pager = view.pagination_class
if hasattr(pager, 'default_pager'):
# Must be a ProxyPagination
pager = pager.default_pager
if issubclass(pager, (PageNumberPagination, LimitOffsetPagination)):
class FakeListSerializer(FakePrevNextListSerializer):
count = IntegerField()
return FakeListSerializer
elif issubclass(pager, CursorPagination):
return FakePrevNextListSerializer
return BaseFakeListSerializer
示例8: test_instance_is_updated_successfully_after_model_serializer_update
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_instance_is_updated_successfully_after_model_serializer_update(self):
class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
class Meta:
model = StringEnumeratedModel
fiedls = ('enumeration', )
instance = StringEnumeratedModel.objects.create(
enumeration=CharTestEnum.FIRST
)
serializer = self.Serializer(data={'enumeration': 'second'})
serializer.is_valid()
serializer.update(instance, serializer.validated_data)
instance.refresh_from_db()
self.assertEqual(
CharTestEnum.SECOND,
instance.enumeration
)
示例9: test_instance_is_created_successfully_when_using_custom_choice_builder
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_instance_is_created_successfully_when_using_custom_choice_builder(self):
class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
class Meta:
model = CustomChoiceBuilderEnumeratedModel
fields = ('enumeration', )
current_instance_count = CustomChoiceBuilderEnumeratedModel.objects.count()
serializer = Serializer(data={'enumeration': 'Custom_first'})
self.assertTrue(serializer.is_valid())
instance = serializer.create(serializer.validated_data)
self.assertEqual(
current_instance_count + 1,
CustomChoiceBuilderEnumeratedModel.objects.count()
)
self.assertEqual(
CharTestEnum.FIRST,
instance.enumeration
)
示例10: benchmark
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def benchmark(serializer_fn, repetitions, num_objs=1, data=None):
total_objs = repetitions * num_objs
if not isinstance(serializer_fn, type):
library = 'Marshmallow'
elif issubclass(serializer_fn, serpy.Serializer):
library = 'serpy'
elif issubclass(serializer_fn, rf_serializers.Serializer):
library = 'Django Rest Framework'
print('Serializing {} objects using {}'.format(total_objs, library))
if data is None:
data = {}
objs = [Obj(**data) for i in range(num_objs)]
many = num_objs > 1
if not many:
objs = objs[0]
t1 = time.time()
for i in range(repetitions):
serializer_fn(objs, many=many).data
total_time = time.time() - t1
print('Total time: {}'.format(total_time))
print('Objs/s : {}\n'.format(int(total_objs / total_time)))
return total_time
示例11: drf_router
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def drf_router():
"""
DRF Router as a lazy object because it needs to import User model which
can't be done until after django.setup()
"""
from django.contrib.auth.models import User
from rest_framework import routers
from rest_framework import serializers
from rest_framework import viewsets
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID", read_only=True)
username = serializers.CharField(max_length=200)
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
router = routers.SimpleRouter()
router.register(r"users", UserViewSet)
return router
示例12: test_describe_fields
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_describe_fields(self):
class DummySerializer(serializers.Serializer):
str = serializers.CharField()
int = serializers.IntegerField()
instance = DummySerializer()
result = describe_serializer(instance, include_read_only=False)
self.assertEqual(_flatten_field_data(result), {
'str': {'value': 'string'},
'int': {'value': 'int'}
})
result = describe_serializer(instance, include_read_only=True)
self.assertEqual(_flatten_field_data(result), {
'str': {'value': 'string'},
'int': {'value': 'int'}
})
示例13: test_describe_field_with_complex_default
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_describe_field_with_complex_default(self):
class DummyDefault(object):
doc_format = 'some string format'
class DummySerializer(serializers.Serializer):
field = serializers.CharField(required=False, default=DummyDefault)
instance = DummySerializer()
result = describe_serializer(instance, include_read_only=False)
self.assertEqual(_flatten_field_data(result), {
'field': {
'tags': 'optional, default="some string format"',
'value': 'string'
}
})
result = describe_serializer(instance, include_read_only=True)
self.assertEqual(_flatten_field_data(result), {'field': {'value': 'string'}})
示例14: test_describe_nested_serializer
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_describe_nested_serializer(self):
class DummyNestedSerializer(serializers.Serializer):
field = serializers.CharField()
class DummySerializer(serializers.Serializer):
top_level = DummyNestedSerializer()
instance = DummySerializer()
result = describe_serializer(instance, True)
self.assertEqual(_flatten_field_data(result), {
'top_level': {
'value': {
'field': {'value': 'string'}
}
}
})
示例15: test_describe_nested_serializer_many
# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import Serializer [as 別名]
def test_describe_nested_serializer_many(self):
class DummyNestedSerializer(serializers.Serializer):
field = serializers.CharField()
class DummySerializer(serializers.Serializer):
top_level = DummyNestedSerializer(many=True)
instance = DummySerializer()
result = describe_serializer(instance, True)
self.assertEqual(_flatten_field_data(result), {
'top_level': {
'value': [{
'field': {'value': 'string'}
}]
}
})