Notice
Recent Posts
Recent Comments
Link
투케이2K
217. (python/파이썬) [AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 DynamoDB 테이블 정보 조회 - DescribeTable 본문
Python
217. (python/파이썬) [AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 DynamoDB 테이블 정보 조회 - DescribeTable
투케이2K 2025. 12. 9. 20:04728x90
[개발 환경 설정]
개발 툴 : Aws / Lambda / Runtime Python 3.13
개발 언어 : python

[소스 코드]
// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------
- 언어 : Python
- 개발 툴 : Aws / Lambda / Runtime Python 3.13
- 개발 기술 : AWS Lambda 이벤트 동작 함수
- 사전) DynamoDB 간단 설명 :
>> Aws DynamoDB 는 모든 규모에서 10밀리초 미만의 성능을 제공하는 서버리스, NoSQL, 완전관리형 데이터베이스입니다 (서버리스 NoSQL 데이터베이스 서비스)
>> Aws DynamoDB 는 규모와 관계없이 일관된 성능이 필요한 운영 워크로드에 맞게 특별히 구축되고 최적화되었습니다.
>> Aws DynamoDB 특징 :
- Serverless (서버리스) : 서버를 프로비저닝하거나 소프트웨어를 패치, 관리, 설치, 유지 보수 또는 운영할 필요가 없으며, 가동 중지가 발생하지 않는 유지 관리를 제공합니다
- NoSQL :
$ 기존의 관계형 데이터베이스보다 향상된 성능, 확장성, 관리성 및 유연성을 제공하도록 특별히 구축되었습니다
$ 다양한 사용 사례를 지원하기 위해 DynamoDB 는 키-값 및 문서 데이터 모델을 모두 지원합니다
- 완전관리형 :
$ DynamoDB 는 설정, 구성, 유지 관리, 고가용성, 하드웨어 프로비저닝, 보안, 백업, 모니터링 등을 처리하며 테이블을 생성할 때 프로덕션 워크로드에 즉시 사용할 수 있습니다.
$ 또한, 업그레이드가 필요하지 않고 가동 중지가 발생하지 않으면서 가용성, 신뢰성, 성능, 보안 및 기능을 지속적으로 개선합니다
- 규모를 따지지 않는 한 자릿수 밀리초의 성능 :
$ DynamoDB 는 모든 규모에서 10밀리초 미만의 성능을 제공하여 관계형 데이터베이스의 성능과 확장성을 개선하기 위해 특별히 개발되었습니다.
$ DynamoDB 는 고성능 워크로드에 최적화되어 있으며 효율적인 데이터베이스 사용을 장려하는 API를 제공합니다 (JOIN 작업과 같이 규모에 비해 비효율적이고 성능이 떨어지는 기능은 생략됩니다)
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------
# ========================================================================
# [Aws] : [boto3 모듈] : IAM 계정 정보 사용해 AWS DynamoDB 테이블 정보 조회 - DescribeTable
# ========================================================================
# [참고] : API Gateway 와 연동 되어 Post 방식으로 Lambda 함수 호출 및 응답 값 반환 수행
# ========================================================================
"""
1. aws lambda python 3.13 런타임 환경 기반
2. boto3 모듈 기본 내장 AWS 사용 모듈
3. import ClientError : AWS SDK for Python 인 boto3 에서 발생할 수 있는 예외 중 하나로, AWS 서비스 호출 중 오류가 발생했을 때 사용됩니다
"""
# ========================================================================
import json
import boto3
from botocore.exceptions import ClientError
from decimal import Decimal
def lambda_handler(event, context):
# [event , context 정보 디버깅 로그 출력]
print(f"DLOG = event : {event} / context {context}")
# [Return 반환 Json 변수 선언]
response = {
"statusCode" : 0,
"headers" : {},
"body" : ""
}
# [AWS IAM 계정 AccessKey, SecretKey 변수 선언]
iamAccessKey = "AK..A6"
iamSecretKey = "mP..5J"
iamRegion = "ap-northeast-2" # 리전
# [명시적 인증 정보로 세션 생성]
session = boto3.Session(
aws_access_key_id = iamAccessKey,
aws_secret_access_key = iamSecretKey,
region_name = iamRegion
)
# [AWS 클라이언트 객체 생성]
aws_client = session.client('dynamodb')
try:
# [API 요청 Parmas 지정]
TABLE_NAME = 'iot_device' # ✅ 조회할 테이블 명칭 지정
# [describe_table 호출 및 AWS 다이나모 디비 특정 테이블 정보 조회]
aws_res = aws_client.describe_table(
TableName=TABLE_NAME
)
print(f"DLOG = aws_res : {aws_res}")
# [반환된 데이터에서 Table 정보만 파싱 수행]
# ✅ 조회 된 정보에서 KeySchema : 파티션 키(HASH) / 소트 키(RANGE)
tableInfo = aws_res.get('Table', {})
# [리턴 변수 삽입] : ApiGateWay 응답 반환 설정 : Lambda 통합 요청 사용
response["statusCode"] = 200
response["headers"] = {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*', # CORS 허용 (필요 시)
}
response["body"] = json.dumps({
"data": json.dumps(tableInfo, default=str)
})
except ClientError as e: # AWS 서비스 호출 중 오류 발생 처리
error_code = e.response['Error']['Code']
error_message = e.response['Error']['Message']
# [리턴 변수 삽입]
response["statusCode"] = 400
response["headers"] = {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*', # CORS 허용 (필요 시)
}
response["body"] = json.dumps(
{
"exception" : "ClientError",
"error_code" : error_code,
"error_message" : error_message
}
)
# [리턴 반환 수행]
return response
# ========================================================================
"""
Response:
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": "{\"data\": \"{\\\"AttributeDefinitions\\\": [{\\\"AttributeName\\\": \\\"status\\\", \\\"AttributeType\\\": \\\"N\\\"}, {\\\"AttributeName\\\": \\\"device_id\\\", \\\"AttributeType\\\": \\\"S\\\"}, {\\\"AttributeName\\\": \\\"mac_address\\\", \\\"AttributeType\\\": \\\"S\\\"}], \\\"TableName\\\": \\\"iot_device\\\", \\\"KeySchema\\\": [{\\\"AttributeName\\\": \\\"device_id\\\", \\\"KeyType\\\": \\\"HASH\\\"}, {\\\"AttributeName\\\": \\\"mac_address\\\", \\\"KeyType\\\": \\\"RANGE\\\"}], \\\"TableStatus\\\": \\\"ACTIVE\\\", \\\"CreationDateTime\\\": \\\"2024-12-16 08:40:58.569000+00:00\\\", \\\"ProvisionedThroughput\\\": {\\\"NumberOfDecreasesToday\\\": 0, \\\"ReadCapacityUnits\\\": 0, \\\"WriteCapacityUnits\\\": 0}, \\\"TableSizeBytes\\\": 718686, \\\"ItemCount\\\": 2548, \\\"TableArn\\\": \\\"arn:aws:dynamodb:ap-northeast-2:123456789012:table/iot_device\\\", \\\"TableId\\\": \\\"b4c28972c\\\", \\\"BillingModeSummary\\\": {\\\"BillingMode\\\": \\\"PAY_PER_REQUEST\\\", \\\"LastUpdateToPayPerRequestDateTime\\\": \\\"2024-12-16 08:40:58.569000+00:00\\\"}, \\\"GlobalSecondaryIndexes\\\": [{\\\"IndexName\\\": \\\"iot_device_delstatus_index\\\", \\\"KeySchema\\\": [{\\\"AttributeName\\\": \\\"mac_address\\\", \\\"KeyType\\\": \\\"HASH\\\"}, {\\\"AttributeName\\\": \\\"status\\\", \\\"KeyType\\\": \\\"RANGE\\\"}], \\\"Projection\\\": {\\\"ProjectionType\\\": \\\"INCLUDE\\\", \\\"NonKeyAttributes\\\": [\\\"model\\\", \\\"expire_datetime\\\", \\\"create_datetime\\\", \\\"status\\\", \\\"device_id\\\", \\\"update_datetime\\\", \\\"brand\\\"]}, \\\"IndexStatus\\\": \\\"ACTIVE\\\", \\\"ProvisionedThroughput\\\": {\\\"NumberOfDecreasesToday\\\": 0, \\\"ReadCapacityUnits\\\": 0, \\\"WriteCapacityUnits\\\": 0}, \\\"IndexSizeBytes\\\": 718686, \\\"ItemCount\\\": 2548, \\\"IndexArn\\\": \\\"arn:aws:dynamodb:ap-northeast-2:123456789012:table/iot_device/index/iot_device_delstatus_index\\\", \\\"WarmThroughput\\\": {\\\"ReadUnitsPerSecond\\\": 12000, \\\"WriteUnitsPerSecond\\\": 4000, \\\"Status\\\": \\\"ACTIVE\\\"}}], \\\"DeletionProtectionEnabled\\\": false, \\\"WarmThroughput\\\": {\\\"ReadUnitsPerSecond\\\": 12000, \\\"WriteUnitsPerSecond\\\": 4000, \\\"Status\\\": \\\"ACTIVE\\\"}}\"}"
}
"""
# ========================================================================
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------
[Aws NoSQL DynamoDB Service] Aws Dynamo DB 다이나모 디비 개념 및 설명 정리
https://kkh0977.tistory.com/7627
https://blog.naver.com/kkh0977/223734725747?trackingCode=blog_bloghome_searchlist
[Aws NoSQL DynamoDB Service] AWS 콘솔에서 다이나모 데이터베이스 ( Dynamo DB ) 테이블에 저장 된 데이터 조회 방법
https://blog.naver.com/kkh0977/223933617765?trackingCode=blog_bloghome_searchlist
[AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 다이나모 DB ( DynamoDB ) 테이블 목록 조회
https://blog.naver.com/kkh0977/223990664323
[Amazon API Gateway] Aws API Gateway 게이트웨이 설명 정리 - 중개 서버
https://blog.naver.com/kkh0977/223827753479
[Amazon API Gateway] Aws API Gateway 게이트웨이 API 엔드포인트 유형 정리
https://blog.naver.com/kkh0977/223911565693
[Aws Lambda] Aws 사이트에서 생성 된 Lambda 람다 검증 함수 리스트 및 내용 소스 코드 확인 방법
https://blog.naver.com/kkh0977/223765198383
[AWS] Lambda 람다 함수 수행 errorType Sandbox.Timedout 에러 발생
https://blog.naver.com/kkh0977/223962778768
// --------------------------------------------------------------------------------------
728x90
반응형
'Python' 카테고리의 다른 글
Comments
