Newbie to python here. I am changing some code which handles dynamodb write from sync to async, to reduce the latency. Current source code uses boto3
to connect to dynamodb:
import boto3
"""
Create dynamodb connection
"""
def _create_dynamo_connection(self):
dynamodb = boto3.resource('dynamodb')
return dynamodb
"""
Write to dynamodb
"""
def _write_to_dynamodb(self, dynamodb, data):
table = dynamodb.Table(DYNAMODB_TABLE)
data_entry = json.loads(json.dumps(data))
# The put_item takes time and we would want to execute the write step without wait
aws_response = table.put_item(Item=data_entry)
In order to make the write function from synchronous to asynchronous approach, initially I was thinking of using aioboto3
(lib) replacing boto3
, but after seeing the example code, it seems like the dynamodb is created with with
clause and cannot be returned. This makes the syntax very different from the current
import asyncio
import aioboto3
async def main():
session = aioboto3.Session()
async with session.resource('dynamodb', region_name='eu-central-1') as dynamo_resource:
table = await dynamo_resource.Table('test_table')
await table.put_item(
Item={'pk': 'test1', 'col1': 'some_data'}
)
I am wondering: if the only need is to make the "write" async, can I just make minor modification of the _write_to_dynamodb()
method? Will I be able to have a workaround without the aioboto3
but with asyncio
. If so, what will the syntax look like?