本文整理匯總了Python中marshmallow.fields.Number方法的典型用法代碼示例。如果您正苦於以下問題:Python fields.Number方法的具體用法?Python fields.Number怎麽用?Python fields.Number使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類marshmallow.fields
的用法示例。
在下文中一共展示了fields.Number方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: inline
# 需要導入模塊: from marshmallow import fields [as 別名]
# 或者: from marshmallow.fields import Number [as 別名]
def inline(self, field, context):
# type: (fields.Field, JitContext) -> Optional[str]
"""Generates a template for inlining string serialization.
For example, generates "float(value) if value is not None else None"
to serialize a float. If `field.as_string` is `True` the result will
be coerced to a string if not None.
"""
if (is_overridden(field._validated, fields.Number._validated) or
is_overridden(field._serialize, fields.Number._serialize) or
field.num_type not in (int, float)):
return None
result = field.num_type.__name__ + '({0})'
if field.as_string and context.is_serializing:
result = 'str({0})'.format(result)
if field.allow_none is True or context.is_serializing:
# Only emit the Null checking code if nulls are allowed. If they
# aren't allowed casting `None` to an integer will throw and the
# slow path will take over.
result += ' if {0} is not None else None'
return result
示例2: validate_positive_number
# 需要導入模塊: from marshmallow import fields [as 別名]
# 或者: from marshmallow.fields import Number [as 別名]
def validate_positive_number(data: Number) -> None:
"""Check that a value is a positive number."""
if not data > 0:
raise ValidationError("Not a positive number", data)
示例3: validate_decimal
# 需要導入模塊: from marshmallow import fields [as 別名]
# 或者: from marshmallow.fields import Number [as 別名]
def validate_decimal(data: Number) -> None:
"""Check that a value is a float between 0 and 1 inclusive."""
if not 0 <= data <= 1:
raise ValidationError("Not in valid range, expected a float between 0 and 1")
示例4: handle_range
# 需要導入模塊: from marshmallow import fields [as 別名]
# 或者: from marshmallow.fields import Number [as 別名]
def handle_range(schema, field, validator, parent_schema):
"""Adds validation logic for ``marshmallow.validate.Range``, setting the
values appropriately ``fields.Number`` and it's subclasses.
Args:
schema (dict): The original JSON schema we generated. This is what we
want to post-process.
field (fields.Field): The field that generated the original schema and
who this post-processor belongs to.
validator (marshmallow.validate.Range): The validator attached to the
passed in field.
parent_schema (marshmallow.Schema): The Schema instance that the field
belongs to.
Returns:
dict: New JSON Schema that has been post processed and
altered.
Raises:
UnsupportedValueError: Raised if the `field` is not an instance of
`fields.Number`.
"""
if not isinstance(field, fields.Number):
raise UnsupportedValueError(
"'Range' validator for non-number fields is not supported"
)
if validator.min is not None:
# marshmallow 2 includes minimum by default
# marshmallow 3 supports "min_inclusive"
min_inclusive = getattr(validator, "min_inclusive", True)
if min_inclusive:
schema["minimum"] = validator.min
else:
schema["exclusiveMinimum"] = validator.min
if validator.max is not None:
# marshmallow 2 includes maximum by default
# marshmallow 3 supports "max_inclusive"
max_inclusive = getattr(validator, "max_inclusive", True)
if max_inclusive:
schema["maximum"] = validator.max
else:
schema["exclusiveMaximum"] = validator.max
return schema
示例5: parseDEI
# 需要導入模塊: from marshmallow import fields [as 別名]
# 或者: from marshmallow.fields import Number [as 別名]
def parseDEI(self,
xbrl,
ignore_errors=0):
"""
Parse DEI from our XBRL soup and return a DEI object.
"""
dei_obj = DEI()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
level=logging.ERROR,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(__name__)
else:
logger = None
trading_symbol = xbrl.find_all(name=re.compile("(dei:tradingsymbol)",
re.IGNORECASE | re.MULTILINE))
dei_obj.trading_symbol = \
self.data_processing(trading_symbol, xbrl,
ignore_errors, logger,
options={'type': 'String',
'no_context': True})
company_name = xbrl.find_all(name=re.compile("(dei:entityregistrantname)",
re.IGNORECASE | re.MULTILINE))
dei_obj.company_name = \
self.data_processing(company_name, xbrl,
ignore_errors, logger,
options={'type': 'String',
'no_context': True})
shares_outstanding = xbrl.find_all(name=re.compile("(dei:entitycommonstocksharesoutstanding)",
re.IGNORECASE | re.MULTILINE))
dei_obj.shares_outstanding = \
self.data_processing(shares_outstanding, xbrl,
ignore_errors, logger,
options={'type': 'Number',
'no_context': True})
public_float = xbrl.find_all(name=re.compile("(dei:entitypublicfloat)",
re.IGNORECASE | re.MULTILINE))
dei_obj.public_float = \
self.data_processing(public_float, xbrl,
ignore_errors, logger,
options={'type': 'Number',
'no_context': True})
return dei_obj
示例6: data_processing
# 需要導入模塊: from marshmallow import fields [as 別名]
# 或者: from marshmallow.fields import Number [as 別名]
def data_processing(self,
elements,
xbrl,
ignore_errors,
logger,
context_ids=[],
**kwargs):
"""
Process a XBRL tag object and extract the correct value as
stated by the context.
"""
options = kwargs.get('options', {'type': 'Number',
'no_context': False})
if options['type'] == 'String':
if len(elements) > 0:
return elements[0].text
if options['no_context'] == True:
if len(elements) > 0 and XBRLParser().is_number(elements[0].text):
return elements[0].text
try:
# Extract the correct values by context
correct_elements = []
for element in elements:
std = element.attrs['contextref']
if std in context_ids:
correct_elements.append(element)
elements = correct_elements
if len(elements) > 0 and XBRLParser().is_number(elements[0].text):
decimals = elements[0].attrs['decimals']
if decimals is not None:
attr_precision = decimals
if xbrl.precision != 0 \
and xbrl.precison != attr_precision:
xbrl.precision = attr_precision
if elements:
return XBRLParser().trim_decimals(elements[0].text,
int(xbrl.precision))
else:
return 0
else:
return 0
except Exception as e:
if ignore_errors == 0:
raise XBRLParserException('value extraction error')
elif ignore_errors == 1:
return 0
elif ignore_errors == 2:
logger.error(str(e) + " error at " +
''.join(elements[0].text))
# Preprocessing to fix broken XML
# TODO - Run tests to see if other XML processing errors can occur