使用适配器在sqlite3中使用decimal和money的问题

Fru*_*ted 5 python sqlite currency decimal

使用sqlite3作为数据库,我想保留几个decimal.Decimal值,一个百分比另一个美元金额.但是我在超过20,000个条目上使用sum(金额)时遇到了问题.这是几美元.

我想过使用适配器来节省分数,然后聚合应该有效.

sqlite3.register_adapter(decimal.Decimal, lambda x:str(x))
sqlite3.register_adapter(decimal.Decimal, lambda x:int(x*100))
Run Code Online (Sandbox Code Playgroud)

但是,我现在需要两个类,因为我不能使用同一个类.试图将Decimal子类化成一个问题因为它本身使用了Decimal.精细.我将复制decimal.py并用Money | money替换每个Decimal | decimal的出现.

$ copy decimal.py money.py
$ sed -e "s/Decimal/Money/g" -e "s/decimal/money/g" -i money.py
$ money.py

所有单元测试都有效.我现在尝试,我得到一个"可能不受支持的类型"错误.我改变转换器,使用基本类型.我只是无法让它正常工作,我对这个问题没有更好的想法.

我需要一些帮助,下面有一个示例.关于如何使用标准库使其工作或更好的解决方案的想法?

import decimal
import money
import sqlite3

sqlite3.register_adapter(decimal.Decimal, lambda x:str(x))
sqlite3.register_converter('decimal', decimal.Decimal)
sqlite3.register_adapter(money.Money, lambda x: int(value*100))
sqlite3.register_converter('intcents', lambda x: money.Money(x)/100)

conn = sqlite3.connect(":memory:",
        detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
cursor.executescript("CREATE TABLE example(rate decimal, amount intcents)")

for x in (1,1,1,2,2,2,3,3,3):
    rate = decimal.Decimal(str(x))/100
    amount = money.Money(str(rate))

    try:
        cursor.execute("INSERT INTO example VALUES(?,?)", (rate, amount))
    except:
        print (rate, amount)
        raise

cursor.execute("""SELECT sum(rate), sum(amount) FROM example""")
print cursor.fetchone()
cursor.execute("""SELECT sum(rate) as "t [decimal]", sum(amount)as "a [intcents]"FROM example""")
print cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)

Fru*_*ted 0

问题出在register_adapter 上。奇怪的是,它并没有导致给我一个 NameError 。另一种解决方案需要对每个输入和输出进行处理。这将否定register_adapter和register_converter的原因。通过注释中的语法修复,它运行得很好。