0
1

More than 1 year has passed since last update.

FastAPI: DynamoDB のデータを読む

Last updated at Posted at 2022-07-26

CORS に対応しています。

フォルダー構造

$ tree
.
├── dynamo_scan.py
└── main.py
main.py
#
#	main.py
#
#					Jul/26/2022
# ------------------------------------------------------------------
import json
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from dynamo_scan import dynamo_scan
# ------------------------------------------------------------------
app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
def read_root():
	rvalue = {"morning": "おはよう","afternoon": "こんにちは"}
	return rvalue

@app.get("/dynamo/{table_name}")
async def get_dynamo(table_name: str):
	json_str = dynamo_scan(table_name)
	rvalue=json.loads(json_str)
	return rvalue
#
# ------------------------------------------------------------------
dynamo_scan.py
#
#	dynamo_scan.py
#
#					Jul/26/2022
# --------------------------------------------------------------------
import	sys
import  json
import	boto3
from decimal import Decimal

# --------------------------------------------------------------------
def decimal_default_proc(obj):
	if isinstance(obj, Decimal):
		return float(obj)
	raise TypeError
# --------------------------------------------------------------------
def scan_all(table, scan_kwargs):
	items = []
	done = False
	start_key = None
	while not done:
		if start_key:
			scan_kwargs['ExclusiveStartKey'] = start_key
		response = table.scan(**scan_kwargs)
		items.extend(response.get('Items', []))
		start_key = response.get('LastEvaluatedKey', None)
		done = start_key is None
	return items
# --------------------------------------------------------------------
def dynamo_scan(name_table):
	dynamodb = boto3.resource('dynamodb')
#	name_table = "uchida-test-cities"
	table = dynamodb.Table(name_table)
	response = scan_all(table,{})
	json_str = json.dumps(response,default=decimal_default_proc)
	return json_str
#
# --------------------------------------------------------------------

サーバーの起動

uvicorn main:app --reload

クライアントでアクセス

http http://localhost:8000/dynamo/cities

データを Web で表示する方法はこちら
DynamoDB のデータを web で表示 (FastAPI)

0
1
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
1