Python decimal.DecimalException() Examples
The following are 19
code examples of decimal.DecimalException().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
decimal
, or try the search function
.
Example #1
Source File: fields.py From python with Apache License 2.0 | 6 votes |
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
Example #2
Source File: validators.py From pydantic with MIT License | 6 votes |
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
Example #3
Source File: fields.py From python2017 with MIT License | 6 votes |
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
Example #4
Source File: fields.py From openhgsenti with Apache License 2.0 | 6 votes |
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
Example #5
Source File: fields.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
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
Example #6
Source File: utils.py From MPContribs with MIT License | 6 votes |
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
Example #7
Source File: fields.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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
Example #8
Source File: money.py From clean-architecture with MIT License | 6 votes |
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
Example #9
Source File: fields.py From bioforum with MIT License | 6 votes |
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
Example #10
Source File: fields.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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
Example #11
Source File: serialization.py From msrest-for-python with MIT License | 5 votes |
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)
Example #12
Source File: gps_tool_data_view_utils.py From stdm with GNU General Public License v2.0 | 5 votes |
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
Example #13
Source File: fields.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
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))
Example #14
Source File: fields.py From esdc-ce with Apache License 2.0 | 5 votes |
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
Example #15
Source File: service.py From django-sberbank with BSD 2-Clause "Simplified" License | 4 votes |
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")
Example #16
Source File: resources.py From django-hordak with MIT License | 4 votes |
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)
Example #17
Source File: utils.py From django-polaris with Apache License 2.0 | 4 votes |
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)
Example #18
Source File: endpoints.py From django-polaris with Apache License 2.0 | 4 votes |
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, } ) } )
Example #19
Source File: mediawiki.py From mediawiki with MIT License | 4 votes |
def geosearch( self, latitude=None, longitude=None, radius=1000, title=None, auto_suggest=True, results=10, ): """ Search for pages that relate to the provided geocoords or near the page Args: latitude (Decimal or None): Latitude geocoord; must be \ coercable to decimal longitude (Decimal or None): Longitude geocoord; must be \ coercable to decimal radius (int): Radius around page or geocoords to pull back; \ in meters title (str): Page title to use as a geocoordinate; this has \ precedence over lat/long auto_suggest (bool): Auto-suggest the page title results (int): Number of pages within the radius to return Returns: list: A listing of page titles Raises: ValueError: If either the passed latitutde or longitude are \ not coercable to a Decimal """ def test_lat_long(val): """ handle testing lat and long """ if not isinstance(val, Decimal): error = ( "Latitude and Longitude must be specified either as " "a Decimal or in formats that can be coerced into " "a Decimal." ) try: return Decimal(val) except (DecimalException, TypeError): raise ValueError(error) return val # end local function params = {"list": "geosearch", "gsradius": radius, "gslimit": results} if title is not None: if auto_suggest: title = self.suggest(title) params["gspage"] = title else: lat = test_lat_long(latitude) lon = test_lat_long(longitude) params["gscoord"] = "{0}|{1}".format(lat, lon) raw_results = self.wiki_request(params) self._check_error_response(raw_results, title) return [d["title"] for d in raw_results["query"]["geosearch"]]