def test_compatibility_return_collections(self): """ When the input with ReturnDict and ReturnList collections is processed by camelize() and then by underscorize(), the result should be same. Serializers should be preserved in all nested ReturnDict and ReturnList collections. """ fake_serializer_instance_1 = (42, ) fake_serializer_instance_2 = (42, ) fake_serializer_instance_3 = (42, ) input = ReturnDict( [("title_display", 1), ("a_list", ReturnList([ 1, "two_three", ReturnDict([("threee_four", 5)], serializer=fake_serializer_instance_3) ], serializer=fake_serializer_instance_2)), ("a_tuple", ("one_two", 3))], serializer=fake_serializer_instance_1) result = underscorize(camelize(input)) self.assertEqual(result, input) self.assertIs(result.serializer, input.serializer) self.assertIs(result['a_list'].serializer, input['a_list'].serializer) self.assertIs(result['a_list'][2].serializer, input['a_list'][2].serializer)
def test_return_dict(self): """ camelize() should convert keys in an instance of rest_framework.utils.serializer_helpers.ReturnDict and keep the same serializer. """ fake_serializer_instance = (42, ) input = ReturnDict([("title_display", 1), ("title_field", 2)], serializer=fake_serializer_instance) output = ReturnDict([("titleDisplay", 1), ("titleField", 2)], serializer=fake_serializer_instance) result = camelize(input) self.assertEqual(result, output) self.assertIs(result.serializer, output.serializer)
def post(self, request, identifier, format=None): try: game = Game.objects.get(identifier=identifier) except: return Response(ErrorMessageResponseSerializer( ErrorMessageResponse(api_errors.IDENTIFIER_INVALID_SENT) ).data) if game.status == 'done': return Response(ErrorMessageResponseSerializer( ErrorMessageResponse(api_errors.GAME_DONE) ).data) if request.data.get('position'): data = request.data.dict() data["player"] = request.user.id data["identifier"] = identifier move_serializer = MoveSerializer(data=data) if move_serializer.is_valid(): move = move_serializer.save() return Response(MoveResponseSerializer( MoveResponse(move) ).data) else: errors = move_serializer.errors all_errors = ReturnDict( list(errors.items()) + [("error_code",[1006])], serializer = errors.serializer ) return Response(all_errors,status = status.HTTP_400_BAD_REQUEST) else: return Response(ErrorMessageResponseSerializer( ErrorMessageResponse(api_errors.POSITION_NOT_SENT) ).data)
def _get_error_details(data, default_code=None): """加载错误详情 :param data: 错误对象 :param default_code: 默认错误码 :return: 错误对象 """ if isinstance(data, list): ret = [_get_error_details(item, default_code) for item in data] if isinstance(data, ReturnList): return ReturnList(ret, serializer=data.serializer) return ret elif isinstance(data, dict): ret = { key: _get_error_details(value, default_code) for key, value in data.items() } if isinstance(data, ReturnDict): return ReturnDict(ret, serializer=data.serializer) return ret elif isinstance(data, Trans): return data text = force_text(data) code = getattr(data, 'code', default_code) return exceptions.ErrorDetail(text, code)
def test_no_attributes(self): data = ReturnDict(( ('id', 2), ('parent', 1), ), serializer=FeatureSerializer()) url = self.full_api_reverse('feature-detail', pk=2) output = self.renderer.render(data, self.media_type, self.make_context(url=url)) expected = { 'links': { 'self': url }, 'data': { 'id': '2', 'type': 'features', 'relationships': { 'parent': { 'data': { 'type': 'features', 'id': '1' }, 'links': { 'self': self.full_api_reverse( 'feature-relationships-parent', pk=2), 'related': self.full_api_reverse('feature-parent', pk=2), } } } }, } self.assertJSONEqual(output.decode('utf8'), expected)
def post(self, request, format=None): try: invited_pk = request.data.get('invited') if invited_pk is None: return Response(ErrorMessageResponseSerializer( ErrorMessageResponse(api_errors.INVITED_NOT_SENT) ).data) data = request.data.dict() data["creator"] = request.user.id game_serializer = GameSerializer(data=data) if game_serializer.is_valid(): game = game_serializer.save() return Response(GameResponseSerializer( GameResponse(game) ).data) else: errors = game_serializer.errors all_errors = ReturnDict( list(errors.items()) + [("error_code",[1006])], serializer = errors.serializer ) return Response(all_errors,status = status.HTTP_400_BAD_REQUEST) except: return Response(ErrorMessageResponseSerializer( ErrorMessageResponse(api_errors.ERROR) ).data)
def data(self): data = super(serializers.ModelSerializer, self).data data["questions"] = [] if "id" in data: for answer in Answer.objects.filter(application=data["id"]): data["questions"].append([answer.question.text, answer.text]) return ReturnDict(data, serializer=self)
def rcu(self, serializer): r = dict(serializer.data) try: r.update({ 'servers': [{ 'id': j, 'name': Server.objects.get(pk=j).name } for j in serializer.data['servers']] }) except Exception as e: print(e, '{0} error'.format(self.__class__.__name__)) try: r['policy'] = { 'id': serializer.data['policy'], 'name': Policy.objects.get(pk=serializer.data['policy']).name } except Exception as e: print(e, '{0} error'.format(self.__class__.__name__)) try: r['cache'] = { 'id': serializer.data['cache'], 'name': CacheConfig.objects.get(pk=serializer.data['cache']).name } except Exception as e: print(e, '{0} error'.format(self.__class__.__name__)) return ReturnDict(r, serializer=self)
def test_no_relationships(self): data = ReturnDict(( ('id', 1), ('slug', 'web'), ('mdn_uri', None), ('name', { 'en': 'Web' }), ), serializer=FeatureSerializer()) url = self.full_api_reverse('feature-detail', pk=1) output = self.renderer.render(data, self.media_type, self.make_context(url=url)) expected = { 'links': { 'self': url }, 'data': { 'id': '1', 'type': 'features', 'attributes': { 'slug': 'web', 'mdn_uri': None, 'name': { 'en': 'Web' }, }, }, } self.assertJSONEqual(output.decode('utf8'), expected)
def data(self): if getattr(self, '_processed_data', None) is None: data = super(WithDynamicSerializerMixin, self).data data = SideloadingProcessor(self, data).data if self.envelope else data self._processed_data = ReturnDict(data, serializer=self) return self._processed_data
def data(self): if not hasattr(self, '_sideloaded_data'): data = super(WithDynamicSerializerMixin, self).data self._sideloaded_data = ReturnDict(SideloadingProcessor( self, data).data if self.sideload else data, serializer=self) return self._sideloaded_data
def data(self): total_count = 0 total_price = 0 resp = list() # 获取购物车信息 cart = self.validated_data.get('cart') for each in cart: item = dict() sku = each.get('sku') count = each.get('count') # 获取sku的信息 serializer = GoodsSkuModelSerializer(instance=sku) # 计算当前sku的小计 amount = sku.price * count # 计算总数目 total_count += count # 计算总价格 total_price += amount # 存储信息 item['sku'] = serializer.data item['count'] = count item['amount'] = amount resp.append(item) # 格式化信息 response = { 'total_count': total_price, 'total_price': total_price, 'item': resp } # 返回应答 return ReturnDict(response, serializer=self)
def to_representation(self, instance): """Add addditonal data for the ViewFeatureSerializer. For most features, all the related data is cachable, and no database reads are required with a warm cache. For some features, such as the root node for CSS, the subtree is huge, and the descendant feature PKs won't fit in the cache. In these cases, a couple of database reads are required to get the descendant feature PKs, which are then paginated to reduce the huge amount of related data. """ # Load the paginated descendant features if instance is None: # This happens when OPTIONS is called from browsable API return None self.add_sources(instance) ret = OrderedDict() fields = self._readable_fields for field in fields: attribute = field.get_attribute(instance) assert attribute is not None, ( 'field.get_attribute return None for instance %s, field %s' % (instance, field)) field_ret = field.to_representation(attribute) if isinstance(field, ListSerializer): # Wrap lists of related resources in a ReturnList, so that the # renderer has access to the serializer field_ret = ReturnList(field_ret, serializer=field) ret[field.field_name] = field_ret return ReturnDict(ret, serializer=self)
def camelize(data, **options): # Handle lazy translated strings. ignore_fields = options.get("ignore_fields") or () if isinstance(data, Promise): data = force_text(data) if isinstance(data, dict): if isinstance(data, ReturnDict): new_dict = ReturnDict(serializer=data.serializer) else: new_dict = OrderedDict() for key, value in data.items(): if isinstance(key, Promise): key = force_text(key) if isinstance(key, str) and "_" in key: new_key = re.sub(camelize_re, underscore_to_camel, key) else: new_key = key if key not in ignore_fields and new_key not in ignore_fields: new_dict[new_key] = camelize(value, **options) else: new_dict[new_key] = value return new_dict if is_iterable(data) and not isinstance(data, str): return [camelize(item, **options) for item in data] return data
def test_null_link(self): data = ReturnDict(( ('id', 1), ('slug', 'web'), ('mdn_uri', None), ('name', {'en': 'Web'}), ('parent', None), ('children', [2, 3, 4, 5, 6, 7]), ), serializer=FeatureSerializer()) url = self.api_reverse('feature-detail', pk=1) output = self.renderer.render( data, self.media_type, self.make_context(url=url)) expected = { 'features': { 'id': '1', 'slug': 'web', 'mdn_uri': None, 'name': {'en': 'Web'}, 'links': { 'parent': None, 'children': ['2', '3', '4', '5', '6', '7'] } }, 'links': { 'features.parent': { 'type': 'features', 'href': self.base_url + 'features/{features.parent}', }, 'features.children': { 'type': 'features', 'href': self.base_url + 'features/{features.children}', }, }, } self.assertJSONEqual(output.decode('utf8'), expected)
def data(self): if not hasattr(self, '_processed_data'): data = super(WithDynamicSerializerMixin, self).data data = SideloadingProcessor(self, data).data if self.envelope else data processed_data = ReturnDict(data, serializer=self) self._processed_data = post_process(processed_data) return self._processed_data
def data(self): self._data = {} if self.instance is not None: return self.to_representation(self.instance) for serializer in self.contained_sers: if serializer: self._data.update(serializer.data) return ReturnDict(self._data, serializer=self)
def data(self): # call grandparent's property ret = super(serializers.Serializer, self).data if isinstance(ret, dict): return ReturnDict(ret, serializer=self) if isinstance(ret, list): return ReturnList(ret, serializer=self) return ret
def data(self): """Get the data, after performing post-processing if necessary.""" data = super(DynamicListSerializer, self).data processed_data = ReturnDict( SideloadingProcessor(self, data).data, serializer=self) if self.child.envelope else ReturnList( data, serializer=self) return processed_data
def data(self): ret = super().data try: perfilPhoto = AvatarHasAluno.objects.get( aluno=self.instance).avatar.url except AvatarHasAluno.DoesNotExist: perfilPhoto = None ret.update({"perfilPhoto": perfilPhoto}) return ReturnDict(ret, serializer=self)
def data(self): # 获取响应的url response = getattr(self, 'response', None) # 返回应答 return ReturnDict({ 'pay_url': response, 'msg': '请求成功!' }, serializer=self)
def rcu(self, serializer): r = dict(serializer.data) try: r['pool'] = { 'id': serializer.data['pool'], 'name': Pool.objects.get(pk=serializer.data['pool']).name } except Exception as e: print(e, '{0} error'.format(self.__class__.__name__)) return ReturnDict(r, serializer=self)
def rcu(self, serializer): r = dict(serializer.data) try: r['domaingroups'] = [{ 'id': j, 'name': DomainGroup.objects.get(pk=j).name } for j in r['domaingroups']] except Exception as e: print(e, '{0} error'.format(self.__class__.__name__)) return ReturnDict(r, serializer=self)
def errors(self): ret = super(Serializer, self).errors if isinstance(ret, list) \ and len(ret) == 1 \ and getattr(ret[0], 'code', None) == 'null': # Edge case. Provide a more descriptive error than # "this field may not be null", when no data is passed. detail = ErrorDetail('No data provided', code='null') ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} return ReturnDict(ret, serializer=self)
def data(self): """ Hack to "force" the initial data shown in the HTML "free type form" :return: """ if not self.instance: ret = self.get_default_serialized_data() return ReturnDict(ret, serializer=self) else: data = super().data return data
def data(self): ret = super(serializers.ListSerializer, self).data if isinstance(ret, dict): # Override to make sure dict is preserved return ReturnDict(ret, serializer=self) elif inspect.isgenerator(ret): # Override to make sure the generator is preserved return ReturnGenerator(ret, serializer=self) else: # Normal behavior return ReturnList(ret, serializer=self)
def data(self): """Get the data, after performing post-processing if necessary.""" if not hasattr(self, '_sideloaded_data'): data = super(DynamicListSerializer, self).data if self.child.sideload: self._sideloaded_data = ReturnDict(SideloadingProcessor( self, data).data, serializer=self) else: self._sideloaded_data = ReturnList(data, serializer=self) return self._sideloaded_data
def get_speakers(self, obj): return [ ReturnDict(PrimarySpeakerSerializer( data={ 'thumbnail_url': i.user.get_thumbnail_url(), 'name': i.user.speaker_name, 'github_profile_url': i.user.github_profile_url, 'twitter_profile_url': i.user.twitter_profile_url, 'facebook_profile_url': i.user.facebook_profile_url }).get_initial(), serializer=PrimarySpeakerSerializer) for i in obj.speakers ]
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response: """ Just remove all response data (except 'id') so nobody may get unrestricted data. Special viewsets may override this. """ response = super().create(request, *args, **kwargs) response.data = ReturnDict( id=response.data.get('id'), serializer=response.data.serializer # This kwarg is not send to the client. ) return response
def test_renderer_works_correctly_with_return_dict(self): """ Ensure that rest_framework.utils.serializer_helpers.ReturnDict is serialized correctly. """ rendered = self.renderer.render( data=ReturnDict(self.data, serializer=None), media_type="application/json", renderer_context={}, ) reloaded = orjson.loads(rendered) self.assertEqual(reloaded, self.data)