gpt4 book ai didi

python - 如何使用 Django REST 序列化程序对保留键进行验证?

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:51 24 4
gpt4 key购买 nike

这可能是一个简单的问题,需要眨眼解决方法。但我无法完成它。我现在正在创建 webhook 端点。并停留在 serializer 类我的类无法使用 from 作为类属性

Python 3.6.4
Django==1.11.9
djangorest==3.7.7

@pytest.fixture
def like_object():
"""LIKE object response from Facebook"""
return {
"object": "page",
"entry": [{
"changes": [{
"field": "feed",
"value": {
"item": "reaction",
"verb": "add",
"reaction_type": "like",
"created_time": 1516183830,
"post_id": "1331351323541869_1844740022202994",
"from": {
"name": "Elcoie Sieve",
"id": "1639217166122728"
},
"parent_id": "1331351323541869_1844740022202994"
}
}],
"time": 1516183830, "id": "1331351323541869"
}]
}

序列化器.py

class FacebookReactionSerializer(serializers.Serializer):
"""
value serializer the inner most of the payload
"""
item = serializers.CharField()
verb = serializers.CharField()
reaction_type = serializers.CharField()
created_time = serializers.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(4086831600)]
) # Limit the maximum epoch to 2099 July 4th 7:00AM
post_id = serializers.CharField(max_length=40)
from = FromSerializer()
parent_id = serializers.CharField()

def validate(self, attrs):
"""
`from` is a python reserved word the add _ to distinguish it from them
:param attrs:
:return:
"""
from_ = attrs.get('from')
pass

def create(self, validated_data):
pass

def update(self, instance, validated_data):
pass

尝试:

ffrom = FromSerializer(source='from')

不起作用

尝试2:

class FacebookReactionSerializer(serializers.Serializer):
"""
value serializer the inner most of the payload
"""
item = serializers.CharField()
verb = serializers.CharField()
reaction_type = serializers.CharField()
created_time = serializers.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(4086831600)]
) # Limit the maximum epoch to 2099 July 4th 7:00AM
post_id = serializers.CharField(max_length=40)
from_key = FromSerializer()
parent_id = serializers.CharField()

def to_representation(self, instance):
"""
https://stackoverflow.com/questions/47630356/using-the-reserved-word-class-as-field-name-in-django-and-django-rest-framewor
:param instance:
:return:
"""
data = super().to_representation(instance)
keys = list(data.keys())
keys.insert(keys.index('from_key'), 'from')
keys.remove('from_key')
from_key = data.pop('from_key')
data.update({'from': from_key})
response = OrderedDict((k, data[k]) for k in keys)
return response

def create(self, validated_data):
pass

def update(self, instance, validated_data):
pass

测试用例失败这里是断点

(Pdb) serializer
FacebookReactionSerializer(data={'item': 'reaction', 'verb': 'add', 'reaction_type': 'like', 'created_time': 1516183830, 'post_id': '1331351323541869_1844740022202994', 'from': {'name': 'Krittuch Onnom', 'id': '1639217166122728'}, 'parent_id': '1331351323541869_1844740022202994'}):
item = CharField()
verb = CharField()
reaction_type = CharField()
created_time = IntegerField(validators=[<rest_framework.compat.MinValueValidator object>, <rest_framework.compat.MaxValueValidator object>])
post_id = CharField(max_length=40)
from_key = FromSerializer():
name = CharField()
id = CharField()
parent_id = CharField()
(Pdb) serializer.errors
*** AssertionError: You must call `.is_valid()` before accessing `.errors`.
(Pdb) serializer.is_valid()
False
(Pdb) serializer.errors
{'from_key': ['This field is required.']}

尝试3:
还要添加 `._declared_fields['from_key']

class FacebookReactionSerializer(serializers.Serializer):
item = serializers.CharField()
verb = serializers.CharField()
reaction_type = serializers.CharField()
created_time = serializers.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(4086831600)]
) # Limit the maximum epoch to 2099 July 4th 7:00AM
post_id = serializers.CharField(max_length=40)
from_key = FromSerializer()
parent_id = serializers.CharField()

def to_representation(self, instance):
data = super().to_representation(instance)
keys = list(data.keys())
keys.insert(keys.index('from_key'), 'from')
keys.remove('from_key')
from_key = data.pop('from_key')
data.update({'from': from_key})
response = OrderedDict((k, data[k]) for k in keys)
return response

def create(self, validated_data):
pass

def update(self, instance, validated_data):
pass

FacebookReactionSerializer._declared_fields["from"] = serializers.CharField(source="from_key")

调试线:

(Pdb) serializer.is_valid()
False
(Pdb) serializer.errors
{'from_key': ['This field is required.'], 'from': ['Not a valid string.']}

我已经很接近了,但还不够

尝试4.1:

不工作。保持同样的错误。 from_key 仍然保留。我是从 child 序列化器编写的。我必须使用 FromSerializer 而不是 CharField

    class FacebookReactionSerializer(serializers.Serializer):
"""
value serializer the inner most of the payload
"""
item = serializers.CharField()
verb = serializers.CharField()
reaction_type = serializers.CharField()
created_time = serializers.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(4086831600)]
) # Limit the maximum epoch to 2099 July 4th 7:00AM
post_id = serializers.CharField(max_length=40)
from_key = FromSerializer()
parent_id = serializers.CharField()

def create(self, validated_data):
pass

def update(self, instance, validated_data):
pass


FacebookReactionSerializer._declared_fields["from"] = FromSerializer(source="from_key")

我现在可以添加 from 作为 key 。但它不会从验证逻辑中删除 from_key

(Pdb) serializer
FacebookReactionSerializer(data={'item': 'reaction', 'verb': 'add', 'reaction_type': 'like', 'created_time': 1516183830, 'post_id': '1331351323541869_1844740022202994', 'from': {'name': 'Krittuch Onnom', 'id': '1639217166122728'}, 'parent_id': '1331351323541869_1844740022202994'}):
item = CharField()
verb = CharField()
reaction_type = CharField()
created_time = IntegerField(validators=[<rest_framework.compat.MinValueValidator object>, <rest_framework.compat.MaxValueValidator object>])
post_id = CharField(max_length=40)
from_key = FromSerializer():
name = CharField()
id = CharField()
parent_id = CharField()
from = FromSerializer(source='from_key'):
name = CharField()
id = CharField()
(Pdb) serializer.is_valid()
False
(Pdb) serializer.errors
{'from_key': ['This field is required.']}

问题:
from(保留字)是 key 并且该键是 python 类属性时,您的解决方法是什么?

最佳答案

@cezar 非常感谢!
解决办法就是这么简单!我一开始很困惑。因为给定的解决方案使用的是 ModelSerializer,所以您必须放置字段并与模型属性耦合。

在我的示例中是简单的Serializer,我不需要它们中的任何一个。

从现在开始,我将通过 Serializer 类来解决此类问题

class FacebookReactionSerializer(serializers.Serializer):
"""
value serializer the inner most of the payload
"""
item = serializers.CharField()
verb = serializers.CharField()
reaction_type = serializers.CharField()
created_time = serializers.IntegerField(
validators=[MinValueValidator(0), MaxValueValidator(4086831600)]
) # Limit the maximum epoch to 2099 July 4th 7:00AM
post_id = serializers.CharField(max_length=40)
parent_id = serializers.CharField()

def create(self, validated_data):
pass

def update(self, instance, validated_data):
pass


FacebookReactionSerializer._declared_fields["from"] = FromSerializer()

这是我的调试行

(Pdb) serializer
FacebookReactionSerializer(data={'item': 'reaction', 'verb': 'add', 'reaction_type': 'like', 'created_time': 1516183830, 'post_id': '1331351323541869_1844740022202994', 'from': {'name': 'Krittuch Onnom', 'id': '1639217166122728'}, 'parent_id': '1331351323541869_1844740022202994'}):
item = CharField()
verb = CharField()
reaction_type = CharField()
created_time = IntegerField(validators=[<rest_framework.compat.MinValueValidator object>, <rest_framework.compat.MaxValueValidator object>])
post_id = CharField(max_length=40)
parent_id = CharField()
from = FromSerializer():
name = CharField()
id = CharField()
(Pdb) serializer.is_valid()
True

关于python - 如何使用 Django REST 序列化程序对保留键进行验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48441193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com