feat: 增加登录页面、学时查询和定时同步
This commit is contained in:
+75
@@ -0,0 +1,75 @@
|
||||
"""登录、使用者记录和定时配置接口。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db import get_db, init_db
|
||||
from app.service import list_accounts, list_schedules, login_and_store, public_account, public_schedule, save_schedule
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="EunivTools", lifespan=lifespan)
|
||||
|
||||
|
||||
class LoginBody(BaseModel):
|
||||
employee_id: str = Field(min_length=1, max_length=32)
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
|
||||
class ScheduleBody(BaseModel):
|
||||
employee_id: str = Field(min_length=1, max_length=32)
|
||||
run_time: str = Field(pattern=r"^\d{2}:\d{2}$")
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/login")
|
||||
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
||||
try:
|
||||
account = login_and_store(db, body.employee_id.strip(), body.password)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return public_account(account)
|
||||
|
||||
|
||||
@app.get("/api/accounts")
|
||||
def accounts(db: Session = Depends(get_db)) -> list[dict]:
|
||||
return [public_account(item) for item in list_accounts(db)]
|
||||
|
||||
|
||||
@app.get("/api/schedules")
|
||||
def schedules(db: Session = Depends(get_db)) -> list[dict]:
|
||||
return [public_schedule(item) for item in list_schedules(db)]
|
||||
|
||||
|
||||
@app.post("/api/schedules")
|
||||
def upsert_schedule(body: ScheduleBody, db: Session = Depends(get_db)) -> dict:
|
||||
hour, minute = body.run_time.split(":")
|
||||
if not (0 <= int(hour) <= 23 and 0 <= int(minute) <= 59):
|
||||
raise HTTPException(status_code=400, detail="时间格式应为 HH:MM")
|
||||
try:
|
||||
schedule = save_schedule(db, body.employee_id.strip(), body.run_time, body.enabled)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
return public_schedule(schedule)
|
||||
|
||||
|
||||
_dist = Path(__file__).resolve().parents[1] / "web" / "dist"
|
||||
if _dist.is_dir():
|
||||
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")
|
||||
Reference in New Issue
Block a user