I have the following code:
def create_report_and_update_user(db_client, report_info):
# TODO:: This will correctly perform operations, but will return a __enter__ error. Figure out why...
report_info = json.loads(json.dumps(report_info), parse_float=Decimal)
user_email = report_info["email"]
report_id = (
"R-" + str(uuid.uuid4())
if not report_info.get("report_id")
else report_info.get("report_id")
)
report_data = {
"report_id": report_id,
"creation_date": str(datetime.now()),
"email": user_email,
"loan_details": report_info["loan_details"],
"purchase_details": report_info["purchase_details"],
"property_details": report_info["property_details"],
"monthly_budget": report_info["monthly_budget"],
}
serializer = TypeSerializer()
report_data = {
key: serializer.serialize(value) for key, value in report_data.items()
}
try:
print("open is assigned to %r" % open)
with db_client.transact_write_items(
TransactItems=[
{
"Put": {
"TableName": REPORTS_TABLE_NAME,
"Item": report_data,
"ConditionExpression": "attribute_not_exists(report_id)",
}
},
]
) as response:
print("Inside transact_write_items")
return response
except Exception as e:
print("HERE: ", e)
However, I'm getting "HERE: enter" printed out to console. What is strange is that my DynamoDB table does properly add a new entry.
I saw another stackoverflow post that advised typing print("open is assigned to %r" % open)
, but I get open is assigned to <built-in function open>
as expected. I don't remember ever overwritting the open
keyword...
Not sure if it will help, but I'm using Windows and testing via sam cli. To run the following code, I use : npx cdk ls; sam local invoke ReportManager-Lambda -t ./cdk.out/GlobalStack.template.json -e .\events\create_report.json
I'm going to take my comment above and turn it into an official answer. You are using with
incorrectly. I get the exact behavior shown above when I write:
try:
with [] as response:
print('hello')
except Exception as e:
print("here", e)
Your code above should just be:
response = db_client.transact_write_items(....)
Because you wrote:
with db_client.transact_write_items(.....) as response:
Python is evaluating the expression (which is succeeding, as you noted), and looking at the resulting value (result
) and attempting to set response = result.__enter__()
.
The result of the transact_write_items()
call has no __enter__
method, and you get the error seen.