我完全被这个错误迷住了,我正试图上传到DynamoDb。我正在试图上传一个Shodan响应到一个表。
response = [{<nested_JSON>}, {<nested_JSON>}, {<nested_JSON>}]
for i in response:
test = loads(dumps(item), parse_float=Decimal)
old_dic_with_decimals = replace_decimals(test)
new_dict_with_decimals_as_strings = loads(dumps(old_dic_with_decimals))
dynamodb.table.put_item(Item=new_dict_with_decimals_as_strings)但是我在put_item函数上得到了这个错误。
[ERROR] Inexact: [<class 'decimal.Inexact'>, <class 'decimal.Rounded'>]
我打印了输出an can确认响应中没有十进制类。下面是我将小数转换为字符串的函数:
def replace_decimals(obj):
if isinstance(obj, list):
for i in range(len(obj)):
obj[i] = replace_decimals(obj[i])
return obj
elif isinstance(obj, dict):
for k, v in obj.items():
obj[k] = replace_decimals(obj[k])
return obj
elif isinstance(obj, Decimal):
ctx = Context(prec=4)
# In my original code I'm converting to int or float, comment the line above if necessary.
if obj % 1 == 0:
my_decimal = ctx.create_decimal_from_float(int(obj))
obj = str(my_decimal)
return obj
else:
my_decimal = ctx.create_decimal_from_float(float(obj))
obj = str(my_decimal)
return obj
else:
return obj我不知道为什么Dynamodb会抛出这个错误。在我试图发送到Dynamodb的响应中,绝对没有小数。我已经尝试了几乎所有的建议,我可以找到堆栈溢出,但没有运气。这里的任何帮助都将不胜感激!
发布于 2022-08-02 15:59:12
在github:https://gist.github.com/lbenitez000/85fb43e40a7839e13405上找到这个猴子补丁后,我解决了这个问题
实际上,您必须添加以下内容:
# Monkey patch Decimal's default Context to allow
# inexact and rounded representation of floats
import decimal
from boto.dynamodb.types import DYNAMODB_CONTEXT
# Inhibit Inexact Exceptions
DYNAMODB_CONTEXT.traps[decimal.Inexact] = 0
# Inhibit Rounded Exceptions
DYNAMODB_CONTEXT.traps[decimal.Rounded] = 0这将允许不精确和圆形的浮标表示!希望这对未来的其他人有所帮助:)
https://stackoverflow.com/questions/73210189
复制相似问题