😎

SaaSを開発した時にどの代理店からの顧客かを管理するパラメータを振る方法

2024/04/23に公開

CosmosDBを利用してFastAPIで代理店を管理する方法を以下に示します。

  1. 必要なライブラリのインストール:
pip install fastapi uvicorn azure-cosmos
  1. CosmosDBの設定:
from azure.cosmos import CosmosClient, PartitionKey

endpoint = "your_cosmosdb_endpoint"
key = "your_cosmosdb_key"
database_name = "your_database_name"
container_name = "your_container_name"

client = CosmosClient(endpoint, key)
database = client.create_database_if_not_exists(id=database_name)
container = database.create_container_if_not_exists(
    id=container_name, 
    partition_key=PartitionKey(path="/partitionKey"),
    offer_throughput=400
)
  1. FastAPIのセットアップ:
from fastapi import FastAPI, Request, Response, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()

class Agent(BaseModel):
    id: str
    name: str

class User(BaseModel):
    id: str
    name: str
    email: str
    agent_id: str
  1. 代理店の登録:
@app.post("/agents")
async def create_agent(agent: Agent):
    agent_data = agent.dict()
    agent_data["partitionKey"] = agent_data["id"]
    container.create_item(body=agent_data)
    return JSONResponse({"message": "Agent created successfully"})
  1. ユーザーの登録と代理店の紐付け:
@app.post("/users")
async def create_user(user: User):
    user_data = user.dict()
    user_data["partitionKey"] = user_data["id"]
    container.create_item(body=user_data)
    return JSONResponse({"message": "User created successfully"})
  1. 代理店ごとの紹介数の集計:
@app.get("/agents/{agent_id}/referrals")
async def get_referral_stats(agent_id: str):
    query = f"SELECT COUNT(1) AS referral_count FROM c WHERE c.agent_id = '{agent_id}'"
    result = container.query_items(query, enable_cross_partition_query=True)
    referral_count = list(result)[0]["referral_count"]
    return JSONResponse({"agent_id": agent_id, "referral_count": referral_count})

上記の例では、CosmosDBを使用してデータを保存および取得しています。代理店とユーザーの情報は、それぞれAgentUserのPydanticモデルで定義されています。

代理店の登録は/agentsエンドポイントで行い、ユーザーの登録と代理店の紐付けは/usersエンドポイントで行います。代理店ごとの紹介数の集計は、/agents/{agent_id}/referralsエンドポイントで実行されます。

CosmosDBでは、パーティションキーを指定する必要があります。上記の例では、idフィールドをパーティションキーとして使用しています。

Discussion