본문 바로가기

WebDev

Pynamodb Basic Tutorial

Pynamodb Basic Tutorial

*이 글은 Pynamodb 공식 문서를 기반으로 작성했습니다.


DynamoDB를 아주 쉽게 쓸 수 있게 해주는 녀석이다.

나 대신 꽤 많은 일들을 해준다:

  • Connection management
  • Sets for Binary, Number, and Unicode attributes
  • Automatic pagination for bulk operations (정말 맘에 드는 부분)
  • Global secondary indexes
  • Local secondary indexes
  • Complex queries
  • dynamodb local hosting

정말 괜찮지 않은가? 유용하게 써보자!




Basic Tutorial


아직 깊이 들어가진 말고, 간단하게(?) pynamodb를 훑어보자



모델 생성

간단한 모델 생성 예는 아래와 같다

class DatePost(Model):

class Meta:
table_name = 'datepost'
region = 'ap-northeast-1'

coupleid = NumberAttribute(hash_key=True)
created = UTCDateTimeAttribute(range_key=True)
title = UnicodeAttribute()
message = UnicodeAttribute()
tags = UnicodeSetAttribute()
photos = UnicodeSetAttribute()

** Meta table_name과 region을 반드시 입력해야 한다


django model과 같은 느낌으로 굉장히 보기가 좋다. 또한 hash key와 range key를 명시할 수 있다.


추상화해 지원해주는 어트리뷰트도 다양하다.

  • BinaryAttribute
  • BinarySetAttribute
  • UnicodeSetAttribute
  • UnicodeAttribute
  • JSONAttribute
  • BooleanAttribute
  • NumberSetAttribute
  • NumberAttribute
  • UTCDateTimeAttribute (datetime 객체를 사용하고, db에는 문자열로 저장된다)


테이블 생성

DatePost.create(read_capacity_units=1, write_capacity_units=1) 형태로 한다.

추가로 create()에 wait=True를 넣어줄 수 있다. 기본값은 False로, 테이블이 생성될 때까지 기다리지 않고 return한다.



객체 생성, 저장, 수정, 삭제

  • 생성

datepost = DatePost(1234, datetime.datetime.now(), title='im title', message='im msg') 형태로 한다.

hash_key와 range_key를 제외한 녀석은 kwargs형태로 넣어주어야 한다.

  • 저장

datepost.save()

  • 수정

datepost.update_item('title', 'newtitle', action='PUT') 형태로 한다

action은 아래의 값 중 하나를 선택하자. (AWS 메뉴얼을 참조했다)

    • PUT 어트리뷰트가 있다면 추가, 있다면 기존 값 덮어씌운다
    • DELETE 값이 지정되지 않았다면 어트리뷰트 삭제, 지정됐다면 값 삭제. 단, set타입의 경우 지정한 값을 set에서 뺀다. 예를 들어 (a,b,c)에서 (a,c)를 빼 (b)를 만들 수 있다
    • ADD 어트리뷰트가 없다면 지정된 값을 가지도록 추가. 있다면 상황에 따라 하는 일이 달라진다. 출처를 참조하자

참고로 이 수정은 hash_key와 range_key가 아닌 어트리뷰트만 가능하다.

  • 삭제

datepost.delete()



쿼리

DatePost.query(1234, title__begins_with='hello', id__gt=5, name__contains='makerj') 형태로 한다.

결과를 담은 제너레이터 객체가 반환된다. limit=1234 형태로 kwargs를 넣으면 결과 아이템 수를 제한할 수 있다.



객체 세기

  • 전부 다 세기

DatePost.count()

  • 조건부 세기

DatePost.count(1234, title__begins_with='a')

  • 인덱스 된 어트리뷰트에서 세기

DatePost.title_index.count('my_hash_key'))


당연한 말이지만 객체의 개수가 결과로 반환된다.



배치 처리

dynamodb의 제약 조건인 "쓰기 배치 한번에, 최대 아이템 25개 쓰기요청 가능"이 좀 짜증난다. 100번 해야된다면 코드로 일일이 4번 끊어주도록 짜야 하니까.

하지만 pynamodb는 이런 부분을 알아서 처리한다.


pynamodb의 배치 처리는 with 문을 적극 활용했다. 아래의 예제로 설명을 마친다

  • 생성

with UserModel.batch_write() as batch:

    for i in range(100):

        batch.save(UserModel('user-{0}@example.com'.format(i), first_name='Samuel', last_name='Adams'))

  • 획득

user_keys = [('user-{0}@example.com'.format(i)) for i in range(100)]

for item in UserModel.batch_get(user_keys):

    print(item)

  • 삭제

with UserModel.batch_write() as batch:

    items = [UserModel('user-{0}@example.com'.format(x)) for x in range(100)]

    for item in items:

        batch.delete(item)





'WebDev' 카테고리의 다른 글

django facebook login  (0) 2016.02.06
Python으로 현재 컴퓨터가 EC2인지 확인하기  (0) 2016.01.26
DRF file upload (파일 업로드)  (0) 2016.01.23
DRF + CORS + CSRF + AJAX 하에서 개발하기  (0) 2016.01.21
django login 정리  (0) 2016.01.21