当前位置: 首页>>代码示例>>Python>>正文


Python decimal.DecimalException方法代码示例

本文整理汇总了Python中decimal.DecimalException方法的典型用法代码示例。如果您正苦于以下问题:Python decimal.DecimalException方法的具体用法?Python decimal.DecimalException怎么用?Python decimal.DecimalException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在decimal的用法示例。


在下文中一共展示了decimal.DecimalException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: clean_value

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def clean_value(value, unit="", convert_to_percent=False, max_dgts=3):
    """return clean value with maximum digits and optional unit and percent"""
    dgts = max_dgts
    value = str(value) if not isinstance(value, six.string_types) else value
    try:
        value = Decimal(value)
        dgts = len(value.as_tuple().digits)
        dgts = max_dgts if dgts > max_dgts else dgts
    except DecimalException:
        return value
    if convert_to_percent:
        value = Decimal(value) * Decimal("100")
        unit = "%"
    val = "{{:.{}g}}".format(dgts).format(value)
    if unit:
        val += " {}".format(unit)
    return val 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:19,代码来源:utils.py

示例2: to_python

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def to_python(self, value):
        """
        Validates that the input is a decimal number. Returns a Decimal
        instance. Returns None for empty values. Ensures that there are no more
        than max_digits in the number, and no more than decimal_places digits
        after the decimal point.
        """
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        value = smart_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:fields.py

示例3: to_python

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def to_python(self, value):
        """
        Validate that the input is a decimal number. Return a Decimal
        instance or None for empty values. Ensure that there are no more
        than max_digits in the number and no more than decimal_places digits
        after the decimal point.
        """
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        value = str(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:19,代码来源:fields.py

示例4: __init__

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def __init__(self, currency: Type[Currency], amount: Any) -> None:
        if not inspect.isclass(currency) or not issubclass(currency, Currency):
            raise ValueError(f"{currency} is not a subclass of Currency!")
        try:
            decimal_amount = Decimal(amount).normalize()
        except DecimalException:
            raise ValueError(f'"{amount}" is not a valid amount!')
        else:
            decimal_tuple = decimal_amount.as_tuple()
            if decimal_tuple.sign:
                raise ValueError(f"amount must not be negative!")
            elif -decimal_tuple.exponent > currency.decimal_precision:
                raise ValueError(
                    f"given amount has invalid precision! It should have "
                    f"no more than {currency.decimal_precision} decimal places!"
                )

            self._currency = currency
            self._amount = decimal_amount 
开发者ID:Enforcer,项目名称:clean-architecture,代码行数:21,代码来源:money.py

示例5: to_python

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def to_python(self, value):
        """
        Validates that the input is a decimal number. Returns a Decimal
        instance. Returns None for empty values. Ensures that there are no more
        than max_digits in the number, and no more than decimal_places digits
        after the decimal point.
        """
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        value = force_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value 
开发者ID:Yeah-Kun,项目名称:python,代码行数:19,代码来源:fields.py

示例6: to_python

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def to_python(self, value):
        """
        Validates that the input is a decimal number. Returns a Decimal
        instance. Returns None for empty values. Ensures that there are no more
        than max_digits in the number, and no more than decimal_places digits
        after the decimal point.
        """
        if value in validators.EMPTY_VALUES:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        value = smart_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'])
        return value 
开发者ID:blackye,项目名称:luscan-devel,代码行数:19,代码来源:fields.py

示例7: decimal_validator

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def decimal_validator(v: Any) -> Decimal:
    if isinstance(v, Decimal):
        return v
    elif isinstance(v, (bytes, bytearray)):
        v = v.decode()

    v = str(v).strip()

    try:
        v = Decimal(v)
    except DecimalException:
        raise errors.DecimalError()

    if not v.is_finite():
        raise errors.DecimalIsNotFiniteError()

    return v 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:19,代码来源:validators.py

示例8: deserialize_decimal

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def deserialize_decimal(attr):
        """Deserialize string into Decimal object.

        :param str attr: response string to be deserialized.
        :rtype: Decimal
        :raises: DeserializationError if string format invalid.
        """
        if isinstance(attr, ET.Element):
            attr = attr.text
        try:
            return decimal.Decimal(attr)
        except decimal.DecimalException as err:
            msg = "Invalid decimal {}".format(attr)
            raise_with_traceback(DeserializationError, msg, err) 
开发者ID:Azure,项目名称:msrest-for-python,代码行数:16,代码来源:serialization.py

示例9: _valid_number

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def _valid_number(value):
    """
    Validates if number is a decimal
    :param value: Input value
    :return: Decimal value if decimal else None
    :rtype: Decimal or None
    """
    try:
        if value:
            return Decimal(value)
    except (ValueError, DecimalException):
        return None 
开发者ID:gltn,项目名称:stdm,代码行数:14,代码来源:gps_tool_data_view_utils.py

示例10: to_internal_value

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def to_internal_value(self, data):
        """
        Validate that the input is a decimal number and return a Decimal
        instance.
        """

        data = smart_text(data).strip()

        if self.localize:
            data = sanitize_separators(data)

        if len(data) > self.MAX_STRING_LENGTH:
            self.fail('max_string_length')

        try:
            value = decimal.Decimal(data)
        except decimal.DecimalException:
            self.fail('invalid')

        # Check for NaN. It is the only value that isn't equal to itself,
        # so we can use this to identify NaN values.
        if value != value:
            self.fail('invalid')

        # Check for infinity and negative infinity.
        if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')):
            self.fail('invalid')

        return self.quantize(self.validate_precision(value)) 
开发者ID:BeanWei,项目名称:Dailyfresh-B2C,代码行数:31,代码来源:fields.py

示例11: from_native

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def from_native(self, value):
        """
        Validates that the input is a decimal number. Returns a Decimal
        instance. Returns None for empty values. Ensures that there are no more
        than max_digits in the number, and no more than decimal_places digits
        after the decimal point.
        """
        if value in validators.EMPTY_VALUES:
            return None
        value = smart_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'])
        return value 
开发者ID:erigones,项目名称:esdc-ce,代码行数:17,代码来源:fields.py

示例12: fee

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def fee(request: Request) -> Response:
    """
    Definition of the /fee endpoint, in accordance with SEP-0024.
    See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md#fee
    """
    deposit_op = polaris_settings.OPERATION_DEPOSIT
    withdrawal_op = polaris_settings.OPERATION_WITHDRAWAL

    operation = request.GET.get("operation")
    op_type = request.GET.get("type")
    asset_code = request.GET.get("asset_code")
    amount_str = request.GET.get("amount")

    # Verify that the asset code exists in our database:
    asset = Asset.objects.filter(code=asset_code, sep24_enabled=True).first()
    if not asset_code or not asset:
        return render_error_response("invalid 'asset_code'")

    # Verify that amount is provided, and that can be parsed into a decimal:
    try:
        amount = Decimal(amount_str)
    except (DecimalException, TypeError):
        return render_error_response("invalid 'amount'")

    error_resp = None
    # Verify that the requested operation is valid:
    if operation not in (deposit_op, withdrawal_op):
        error_resp = render_error_response(
            f"'operation' should be either '{deposit_op}' or '{withdrawal_op}'"
        )
    # Verify asset is enabled and within the specified limits
    elif operation == deposit_op:
        error_resp = verify_valid_asset_operation(
            asset, amount, Transaction.KIND.deposit
        )
    elif operation == withdrawal_op:
        error_resp = verify_valid_asset_operation(
            asset, amount, Transaction.KIND.withdrawal
        )

    if error_resp:
        return error_resp
    else:
        return Response(
            {
                "fee": registered_fee_func(
                    {
                        "operation": operation,
                        "type": op_type,
                        "asset_code": asset_code,
                        "amount": amount,
                    }
                )
            }
        ) 
开发者ID:stellar,项目名称:django-polaris,代码行数:57,代码来源:endpoints.py

示例13: interactive_args_validation

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def interactive_args_validation(request: Request) -> Dict:
    """
    Validates the arguments passed to the /webapp endpoints

    Returns a dictionary, either containing an 'error' response
    object or the transaction and asset objects specified by the
    incoming request.
    """
    transaction_id = request.GET.get("transaction_id")
    asset_code = request.GET.get("asset_code")
    callback = request.GET.get("callback")
    amount_str = request.GET.get("amount")
    asset = Asset.objects.filter(code=asset_code, sep24_enabled=True).first()
    if not transaction_id:
        return dict(
            error=render_error_response(
                _("no 'transaction_id' provided"), content_type="text/html"
            )
        )
    elif not (asset_code and asset):
        return dict(
            error=render_error_response(
                _("invalid 'asset_code'"), content_type="text/html"
            )
        )
    try:
        transaction = Transaction.objects.get(id=transaction_id, asset=asset)
    except (Transaction.DoesNotExist, ValidationError):
        return dict(
            error=render_error_response(
                _("Transaction with ID and asset_code not found"),
                content_type="text/html",
                status_code=status.HTTP_404_NOT_FOUND,
            )
        )

    # Verify that amount is provided, and that can be parsed into a decimal:
    amount = None
    if amount_str:
        try:
            amount = Decimal(amount_str)
        except (DecimalException, TypeError):
            return dict(error=render_error_response("invalid 'amount'"))

        err_resp = verify_valid_asset_operation(
            asset, amount, transaction.kind, content_type="text/html"
        )
        if err_resp:
            return dict(error=err_resp)

    return dict(transaction=transaction, asset=asset, callback=callback, amount=amount) 
开发者ID:stellar,项目名称:django-polaris,代码行数:53,代码来源:utils.py

示例14: import_obj

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def import_obj(self, obj, data, dry_run):
        F = TransactionCsvImportColumn.TO_FIELDS
        use_dual_amounts = F.amount_out in data and F.amount_in in data

        if F.date not in data:
            raise ValueError("No date column found")

        try:
            date = datetime.strptime(data[F.date], self.date_format).date()
        except ValueError:
            raise ValueError(
                "Invalid value for date. Expected {}".format(dict(DATE_FORMATS)[self.date_format])
            )

        description = data[F.description]

        # Do we have in/out columns, or just one amount column?
        if use_dual_amounts:
            amount_out = data[F.amount_out]
            amount_in = data[F.amount_in]

            if amount_in and amount_out:
                raise ValueError("Values found for both Amount In and Amount Out")
            if not amount_in and not amount_out:
                raise ValueError("Value required for either Amount In or Amount Out")

            if amount_out:
                try:
                    amount = abs(Decimal(amount_out)) * -1
                except DecimalException:
                    raise ValueError("Invalid value found for Amount Out")
            else:
                try:
                    amount = abs(Decimal(amount_in))
                except DecimalException:
                    raise ValueError("Invalid value found for Amount In")
        else:
            if F.amount not in data:
                raise ValueError("No amount column found")
            if not data[F.amount]:
                raise ValueError("No value found for amount")
            try:
                amount = Decimal(data[F.amount])
            except:
                raise DecimalException("Invalid value found for Amount")

        if amount == Decimal("0"):
            raise ValueError("Amount of zero not allowed")

        data = dict(date=date, amount=amount, description=description)
        return super(StatementLineResource, self).import_obj(obj, data, dry_run) 
开发者ID:adamcharnock,项目名称:django-hordak,代码行数:53,代码来源:resources.py

示例15: pay

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import DecimalException [as 别名]
def pay(self, amount, preauth=False, **kwargs):
        session_timeout = self.merchant.get('session_timeout', self.__default_session_timeout)
        currency = self.merchant.get('currency', self.__default_currency_code)
        fail_url = kwargs.get('fail_url', self.merchant.get('fail_url'))
        success_url = kwargs.get('success_url', self.merchant.get('success_url'))
        client_id = kwargs.get('client_id')
        page_view = kwargs.get('page_view', 'DESKTOP')
        details = kwargs.get('details', {})
        description = kwargs.get('description')
        method = 'rest/register' if not preauth else 'rest/registerPreAuth'

        if success_url is None:
            raise ValueError("success_url is not set")

        try:
            amount = Decimal(str(amount))
        except (ValueError, DecimalException):
            raise TypeError(
                "Wrong amount type, passed {} ({}) instead of decimal".format(amount, type(amount)))

        payment = Payment(amount=amount, client_id=client_id, method=Method.WEB, details={
            'username': self.merchant.get("username"),
            'currency': currency,
            'success_url': success_url,
            'fail_url': fail_url,
            'session_timeout': session_timeout,
            'client_id': client_id
        })

        payment.details.update(details)
        payment.save()

        data = {
            'orderNumber': payment.uid.hex,
            'amount': int(amount * 100),
            'returnUrl': success_url,
            'failUrl': fail_url,
            'sessionTimeoutSecs': session_timeout,
            'pageView': page_view,
        }
        if kwargs.get('params'):
            data.update({'jsonParams': json.dumps(kwargs.get('params'))})
        if kwargs.get('client_id'):
            data.update({'clientId': client_id})
        if kwargs.get('description'):
            data.update({'description': description})

        response = self.execute_request(data, method, payment)

        payment.bank_id = response.get('orderId')
        payment.status = Status.PENDING
        payment.details.update({'redirect_url': response.get('formUrl')})
        if kwargs.get('params'):
            payment.details.update(kwargs.get('params'))
        payment.save()

        return payment, payment.details.get("redirect_url") 
开发者ID:madprogrammer,项目名称:django-sberbank,代码行数:59,代码来源:service.py


注:本文中的decimal.DecimalException方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。