基于Python编写一个有趣的年会抽奖系统

  from fastapi import FastAPI, Request

  from fastapi.templating import Jinja2Templates

  from fastapi.staticfiles import StaticFiles

  # from models import Participant, Prize

  # from database import SessionLocal, engine

  from pydantic import BaseModel

  from random import choice

  app = FastAPI()

  app.mount("/static", StaticFiles(directory="static"), name="static")

  templates = Jinja2Templates(directory="templates")

  prizes = []

  participants = []

  class Participant(BaseModel):

  name: str

  class Prize(BaseModel):

  winner: str

  prize: str

  class DatePrize(BaseModel):

  prize: str

  @app.get("/")

  async def root(request: Request):

  return templates.TemplateResponse("index.html", {"request": request})

  @app.post("/participant")

  async def add_participant(participant: Participant):

  participants.append(participant)

  return {"message": "Participant added successfully"}

  @app.post("/draw")

  async def draw_prize(date_prize: DatePrize):

  if not participants:

  return {"message": "No participants available","code":0}

  winner = choice(participants)

  prize = Prize(winner=winner.name,prize=date_prize.prize)

  prizes.append(prize)

  participants.remove(winner)

  return {"message": f"Congratulations {winner.name}, you have won a prize : {date_prize.prize}!","code":1}

  @app.get("/prizes")

  async def get_prizes():

  return {"prizes": [prize.winner for prize in prizes]}

  @app.get("/participants")

  async def get_participants():

  return {"participants": [participant.name for participant in participants]}