我正在尝试获取用户发布的数据,并在保存之前解析它。这是我正在使用的代码,但我不明白为什么它不起作用。
Serializers.py
class MobileDataSerializer(serializers.Serializer):
m = serializers.IntegerField()
o = serializers.CharField(max_length=50)
c = serializers.CharField(max_length=50)
um = serializers.CharField(max_length=1000, blank=True)
cm = serializers.CharField(max_length=1000, blank=True)
p1 = serializers.CharField(max_length=1000, blank=True)
def restore_object(self, attrs, instance=None):
if instance:
instance.m = attrs.get('m', instance.m)
instance.o = attrs.get('o', instance.o)
instance.c = attrs.get('c', instance.c)
instance.um = attrs.get('um', instance.um)
instance.cm = attrs.get('cm', instance.cm)
instance.p1 = attrs.get('p1', instance.p1)
return instance
我的views.py看起来像这样。
@api_view(['POST'])
def data_items(request):
print("test")
if request.method == 'POST':
serializer = MobileDataSerializer(data=request.DATA)
print(serializer.data)
if serializer.is_valid():
#print(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST)
要执行POST请求,我使用以下命令:
curl -X POST http://127.0.0.1:8000/api/network18/ -d "m=1231212&o=afaadas&c=asdasdasd"
我得到的回应是:
{"m": 0, "o": "", "c": "", "um": "", "cm": "", "p1": ""}