Skip to content

Initialise counter automatically #1

@paulmdavies

Description

@paulmdavies

Hi @TheBatch,

Thanks for your very useful post of this code. The only bit I don't like is having to initialise the counter by hand - this seems easy to forget.

I've written a snippet (in python, but I could translate it if you approve) that initialises the counter automatically - it has the disadvantage of consuming more read and write units, but for my use case (counter being incremented probably not more than a few times per day) this is preferable.

import boto3
from boto3.dynamodb.conditions import Attr

table = boto3.resource('dynamodb').Table('counters')

response = table.get_item(
    Key={
        'counterName': 'foo'
    },
    ConsistentRead=True
)
if 'Attributes' not in response:
    try:
        response = table.put_item(
            Item={
                'counterName': 'foo',
                'value': 1
            },
            ConditionExpression=Attr('value').not_exists()
        )
        print(1)
    except Exception as e:
        response = table.update_item(
            Key={
                'counterName': 'foo'
            },
            ReturnValues='UPDATED_NEW',
            ExpressionAttributeValues={
                ':a': 1
            },
            ExpressionAttributeNames={
                '#v': 'value'
            },
            UpdateExpression='SET #v = #v + :a'
        )
        print(response['Attributes']['value'])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions