こちらで定めた仕様を満たすサーバーサイドのプログラムです。
FastAPI で実装しました。
Redis の WebAPI を作成
redis01.py
# --------------------------------------------------------
#
# redis01.py
#
# Jun/08/2021
# --------------------------------------------------------
from fastapi import FastAPI
from pydantic import BaseModel
import redis
# --------------------------------------------------------
class Item(BaseModel):
key: str
class Item_insert(BaseModel):
key: str
value: str
app = FastAPI()
@app.post("/redis_get/")
async def redis_get(item: Item):
key = item.key
rr = redis.Redis(host='localhost', port=6379, db=0)
json_str = rr.get(key).decode()
return json_str
@app.post("/redis_insert/")
async def redis_insert(item_insert: Item_insert):
key = item_insert.key
value = item_insert.value
rr = redis.Redis(host='localhost', port=6379, db=0)
rr.set(key, value)
#
return key
@app.post("/redis_list/")
async def redis_list():
rr = redis.Redis(host='localhost', port=6379, db=0)
keys = rr.keys('*')
return keys
# --------------------------------------------------------
サーバーの起動
uvicorn redis01:app --reload
クライアントからアクセス
キーの一覧
$ http POST http://127.0.0.1:8000/redis_list/
HTTP/1.1 200 OK
content-length: 73
content-type: application/json
date: Tue, 08 Jun 2021 05:38:27 GMT
server: uvicorn
[
"t1858",
"t1857",
"t1856",
"t1854",
"t1853",
"t1855",
"t1852",
"t1851",
"t1859"
]
キーを指定して値の取得
$ http POST http://127.0.0.1:8000/redis_get/ key=t1852
HTTP/1.1 200 OK
content-length: 84
content-type: application/json
date: Tue, 08 Jun 2021 05:39:04 GMT
server: uvicorn
"{\"name\": \"\\u6566\\u8cc0\", \"population\": 41295, \"date_mod\": \"2003-5-10\"}"
値の挿入
$ http POST http://127.0.0.1:8000/redis_insert/ key=t1853 value='{"name": "宇都宮","population": 8751600,"date_mod": "2021-3-17"}'
HTTP/1.1 200 OK
content-length: 7
content-type: application/json
date: Tue, 08 Jun 2021 05:39:35 GMT
server: uvicorn
"t1853"