當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。