python 3货币库,支持十进制精度和货币兑换。
money-lib的Python项目详细描述
货币库
python 3货币库,支持十进制精度和货币兑换。
安装
使用以下命令安装最新版本:
pip install money-lib
用法
可以使用currency_code创建currency对象(必须是字符串和有效的ISO 4217格式:^[A-Z]{3}$
)。
>>>frommoneyimportCurrency>>>currency=Currency('USD')>>>currencyCurrency('USD')
money对象可以使用amount(可以是decimal.Decimal(value)
中的任何有效值)和currency(可以是字符串或Currency(code)
对象)创建。
>>>frommoneyimportMoney>>>money=Money('7.37','USD')>>>moneyMoney(Decimal('7.37'),'USD')
money对象根据约定是不可变的,并且是散列的。创建后,可以使用只读属性amount(decimal.decimal)和currency(currency)访问其内部组件。 amount属性返回四舍五入到货币的正确小数位数的金额。
>>>money=Money('6.831','USD')>>>money.amountDecimal('6.83')>>>money.currencyCurrency('USD')
money可以在money对象、整数(int)和十进制数(decimal.decimal)之间应用大多数算术和比较运算符。
>>>money=Money('5','USD')>>>money/2Money(Decimal('2.5'),'USD')>>>money+Money('10','USD')Money(Decimal('15'),'USD')
只要设置了currency exchange backend,所有比较运算符和算术运算符都支持自动货币转换。 最左边对象的货币具有优先级。
# Assuming the rate from USD to EUR is 2>>>money=Money('7.50','USD')>>>money+Money('5','EUR')Money(Decimal('10.00'),'USD')
money支持不同地区的格式化。
>>>money=Money('13.65','USD')>>>money.format()'$13.65'>>>money.format('pt_PT')'13,65 US$'
货币兑换
货币交换通过设置实现抽象基类money.exchange.BaseBackend
的后端类来工作。
它的api通过money.xrates
以及xrates.backend
和xrates.backend_name
公开。
包括一个简单的概念证明后端money.exchange.SimpleBackend
。
>>>fromdecimalimportDecimal>>>frommoneyimportMoney,xrates>>>xrates.backend='money.exchange.SimpleBackend'>>>xrates.base='USD'>>>xrates.setrate('AAA',Decimal('2'))>>>xrates.setrate('BBB',Decimal('8'))>>>a=Money('1','AAA')>>>b=Money('1','BBB')>>>asserta.to('BBB')==Money('4','BBB')>>>assertb.to('AAA')==Money('0.25','AAA')>>>asserta+b==Money('1.25','AAA')
django集成
模型字段用法:
>>>fromdjango.dbimportmodels>>>frommoneyimportfields,Money>>>classProduct(models.Model):...price=fields.MoneyField(max_digits=19,decimal_places=4,default=Money('10','USD'))
模型查询用法:
# MoneyField creates another field (MoneyField name + '_currency') to store the currency>>>Product.objects.create(price=Money('10','USD'))>>>Product.objects.create(price='10',price_currency='USD')# Get all products where price is greater than 4 and the currency equals 'USD'>>>product=Product.objects.filter(price__gt=4,price_currency='USD').first()>>>product.priceMoney(Decimal('10.0000'),'USD')
学分
基于https://github.com/carlospalol/money的货币兑换支持。
django通过miracle2k对多个数据库列进行建模。
货币数据和格式由Babel提供。