0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DynamoDB Local で pythonを使っての採番処理の作成 採番処理編

Posted at

概要

pythonの採番処理を作成するときにDynamoDBを使うときに開発中に実際のDynamoDBを使うのは・・・という場合DynamoDB Local を使っての開発すると思うのでその方法をまとめていきます。
前回の続きで実際にpythonのプログラムを作成します。

事前準備

  • pythonのインストール(記事作成時は3.7です)。
    • JupyterNotebookなどでも可能です。
  • boto3

実装

  • ソースは以下のようになります。
    • 各種設定値は環境変数から取得するようにしています。ここにACCESS_KEYなどをべたに書くと大変なことになります。
    • sequence_key は固定にしていますが、実際に使うときは引数で受け取るなどしたほうがよいかと。
import os
import boto3

endpoint_url = os.getenv('DYNAMODB_ENDPOINT', 'http://192.168.99.100:8000/')
aws_access_key_id = os.getenv('DYNAMODB_ACCESS_KEY_ID', 'DummyID')
aws_secret_access_key_id = os.getenv('DYNAMODB_SECRET_ACCESS_KEY_ID', 'DummyKey')
aws_region_name = os.getenv('DYNAMODB_REGION', 'ap-northeast-1')

dynamodb = boto3.resource(
    'dynamodb',
    region_name=aws_region_name,
    endpoint_url=endpoint_url,
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key_id
)

sequences = dynamodb.Table('sequences')

res = sequences.update_item(
    Key= {
        'sequence_key': 'TEST_SEQ'
        },
    UpdateExpression="ADD #name :increment",
    ExpressionAttributeNames={
        '#name':'val'
        },
    ExpressionAttributeValues={
        ":increment": int(1)
        },
    ReturnValues="UPDATED_NEW"
)

count=res['Attributes']['val']

print(count)

  • 実行結果は以下のようになります。

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?