CRUD DynamoDB from Python (PynamoDB)

In this post, I am goint to use DynamoDB from PynamoDB.

You may compare the code with CRUD DynamoDB from Python (boto3)


what is PynamoDB?

PynamoDB is "a Pythonic interface for Amazon's DynamoDB"

https://github.com/pynamodb/PynamoDB


install

% pip install pynamodb

% pip list | grep pynamo

pynamodb                           5.0.3


student.py

You can define the entity like:

from pynamodb.attributes import UnicodeAttribute

from pynamodb.models import Model


class Student(Model):

  class Meta:

    table_name = 'student'

    host = 'http://localhost:8000' # region = 'us-east-1'

    write_capacity_units = 5 

    read_capacity_units = 5 


  id = UnicodeAttribute(hash_key=True)

  grade = UnicodeAttribute(null=True)

You may remove the host = localhost (and optionally specify the region) to run it on the cloud.


test.py

from student import Student


# create table (wait for creation)

if not Student.exists():

  Student.create_table(wait=True)


# insert

s1 = Student('001')

s1.save()

print(s1.id) # 001


Student('002', grade='B').save()


# select

s2 = Student.get('002')

print(s2.id + ',' + s2.grade) # 002,B


# update

s1.update(actions=[

  Student.grade.set('A')

])

print(s1.id + ',' + s1.grade) # 001,A


# delete

s1.delete()


# drop table

Student.delete_table()


Comments

Popular posts from this blog

Selenide: Quick Start

Minikube Installation for M1 Mac

Server Testing Tools: Serverspec, InSpec, Testinfra, Goss