我希望有人可以就此提出建议:尽管数据正确,但我的序列化程序返回一个空字符串。
#!/usr/bin/perl
print "Content-type: text/html\n\n";
use CGI qw(:standard);
local ( $buffer, @pairs, $pair, $name, $value, %FORM );
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ( $ENV{'REQUEST_METHOD'} eq "POST" ) {
read( STDIN, $buffer, $ENV{'CONTENT_LENGTH'} );
}
else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split( /&/, $buffer );
foreach $pair ( @pairs ) {
( $name, $value ) = split( /=/, $pair );
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
#variables for input text fields
$Item = $FORM{Item};
$Name = $FORM{Name};
$Cost = $FORM{Cost};
$Price = $FORM{Price};
$Quantity = $FORM{Quantity};
#Radio button
$letter = $FORM{letter};
#Validate data is entered in first 2 input boxes
if ( $Item eq "" ) {
print "$Item Field Cannot be Blank";
}
if ( $Name eq "" ) {
print "$Name Field cannot be Blank";
}
#Validate the correct amount is entered
if ( $Cost >= .50 && $Cost <= 1000 ) {
print "$Cost Cost must be between $.50 and $1000";
}
if ( $Price >= 1.00 && $Cost <= 2000 ) {
print "$Price Price must be between $1.00 and $2000";
}
#Validate Category is Chosen
#Validate Quantity on hand not less than 0
if ( $Quantity < 0 ) {
print "$Quantity Quantity on-hand cannot be less than 0";
}
MySerializer:
def foo(self, request, uuid=None):
data = JSONParser().parse(request)
logger.error(data)
serializer = MySerializer(data=data)
logger.error(serializer.data) #Empty JSON string
something.bar(serializer.data, self.request.user)
return Response(status=status.HTTP_201_CREATED)
序列化程序从serializer.data返回的数据: foo1:'',foo2:False,foo3:False
我哪里错了?
答案 0 :(得分:3)
我相信您的答案直接来自rest_framework/serializers.py
:
@property
def data(self):
if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'):
msg = (
'When a serializer is passed a `data` keyword argument you '
'must call `.is_valid()` before attempting to access the '
'serialized `.data` representation.\n'
'You should either call `.is_valid()` first, '
'or access `.initial_data` instead.'
)
raise AssertionError(msg)
答案 1 :(得分:1)
您需要首先使用数据在序列化程序上调用.is_valid()
,然后访问序列化数据(Joey也指出)。
def foo(self, request, uuid=None):
data = JSONParser().parse(request)
logger.error(data)
serializer = MySerializer(data=data)
serializer.is_valid(raise_exception=True) # explicitly call .is_valid() first
logger.error(serializer.data) #Empty JSON string
something.bar(serializer.data, self.request.user)
return Response(status=status.HTTP_201_CREATED)