diff --git a/main.py b/main.py index c258d1d..3541188 100644 --- a/main.py +++ b/main.py @@ -1,14 +1,43 @@ import sqlite3 from contextlib import contextmanager -from datetime import datetime +from datetime import UTC, datetime, timedelta +from html import escape from io import BytesIO -from typing import cast +from typing import Annotated, cast +import jwt import pandas as pd -from fastapi import FastAPI, File, HTTPException, Query, UploadFile +from fastapi import Depends, FastAPI, File, HTTPException, Query, Request, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, StreamingResponse -from pydantic import BaseModel +from pydantic import BaseModel, BeforeValidator + +SECRET_KEY = 'QET5hv3A@148fefo#5#W5x#aF%9Y#8!2' +ALGORITHM = 'HS256' +ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 + + +def create_access_token(data: dict): + to_encode = data.copy() + expire = datetime.now(UTC) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + to_encode.update({'exp': expire}) + return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + + +def verify_token(token: str): + try: + return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + except jwt.PyJWTError as exc: + raise HTTPException(status_code=401, detail='Token 无效') from exc + + +async def require_admin(request: Request): + token = request.headers.get('Authorization', '').replace('Bearer ', '') + payload = verify_token(token) + if payload.get('role') != 'admin': + raise HTTPException(status_code=403, detail='需要管理员权限') + return payload + app = FastAPI(title='文艺汇演评分系统', description='乌鲁木齐群众文化艺术展评') @@ -25,12 +54,20 @@ DB_PATH = 'score_system.db' @contextmanager -def get_db(): +def get_db(write=False): conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row + conn.execute('PRAGMA journal_mode=WAL') + conn.execute('PRAGMA busy_timeout=5000') + conn.execute('PRAGMA foreign_keys=ON') + if write: + conn.execute('BEGIN IMMEDIATE') try: yield conn conn.commit() + except Exception: + conn.rollback() + raise finally: conn.close() @@ -43,13 +80,13 @@ def init_db(): """CREATE TABLE IF NOT EXISTS batches (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, created_at TIMESTAMP)""" ) cursor.execute( - """CREATE TABLE IF NOT EXISTS programs (sn TEXT PRIMARY KEY, name TEXT NOT NULL, unit TEXT, performer TEXT, category TEXT, batch_id INTEGER, order_num INTEGER, created_at TIMESTAMP)""" + """CREATE TABLE IF NOT EXISTS programs (sn TEXT PRIMARY KEY, name TEXT NOT NULL, unit TEXT, performer TEXT, category TEXT, batch_id INTEGER NOT NULL, order_num INTEGER, created_at TIMESTAMP, UNIQUE(batch_id, order_num), FOREIGN KEY (batch_id) REFERENCES batches(id) ON DELETE CASCADE ON UPDATE CASCADE)""" ) cursor.execute( """CREATE TABLE IF NOT EXISTS judges (id TEXT PRIMARY KEY, name TEXT NOT NULL, order_num INTEGER, created_at TIMESTAMP)""" ) cursor.execute( - """CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, judge_id TEXT NOT NULL, program_sn TEXT NOT NULL, content_score REAL, stage_score REAL, art_score REAL, overall_score REAL, comment TEXT, updated_at TIMESTAMP, UNIQUE(judge_id, program_sn))""" + """CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, judge_id TEXT NOT NULL, program_sn TEXT NOT NULL, content_score REAL, stage_score REAL, art_score REAL, overall_score REAL, comment TEXT, updated_at TIMESTAMP, UNIQUE(judge_id, program_sn), FOREIGN KEY (program_sn) REFERENCES programs(sn) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (judge_id) REFERENCES judges(id) ON DELETE CASCADE ON UPDATE CASCADE)""" ) cursor.execute( """CREATE TABLE IF NOT EXISTS admins (id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, created_at TIMESTAMP)""" @@ -113,60 +150,69 @@ init_db() # ==================== Pydantic模型 ==================== +def escape_html(value: str) -> str: + if value is None: + return '' + return escape(str(value).strip()) + + +EscapedStr = Annotated[str, BeforeValidator(escape_html)] + + class AdminLogin(BaseModel): - username: str - password: str + username: EscapedStr + password: EscapedStr class JudgeLogin(BaseModel): - judge_id: str - judge_name: str + judge_id: EscapedStr + judge_name: EscapedStr class JudgeCreate(BaseModel): - id: str - name: str + id: EscapedStr + name: EscapedStr class JudgeUpdate(BaseModel): - name: str + name: EscapedStr class ProgramCreate(BaseModel): - sn: str - name: str - unit: str - performer: str - category: str + sn: EscapedStr + name: EscapedStr + unit: EscapedStr + performer: EscapedStr + category: EscapedStr batch_id: int class ProgramUpdate(BaseModel): - name: str - unit: str - performer: str - category: str + name: EscapedStr + unit: EscapedStr + performer: EscapedStr + category: EscapedStr batch_id: int class BatchCreate(BaseModel): - name: str + name: EscapedStr class ScoreDetailUpdate(BaseModel): - program_sn: str - field: str + program_sn: EscapedStr + field: EscapedStr value: float | None = None class ScoreBatchUpdate(BaseModel): - program_sn: str - judge_scores: dict[str, float | None] + program_sn: EscapedStr + judge_scores: dict[EscapedStr, float | None] class CommentUpdate(BaseModel): - program_sn: str - comment: str + program_sn: EscapedStr + comment: EscapedStr class AwardSettings(BaseModel): @@ -176,14 +222,14 @@ class AwardSettings(BaseModel): class AwardNamesSettings(BaseModel): - first_name: str - second_name: str - third_name: str + first_name: EscapedStr + second_name: EscapedStr + third_name: EscapedStr class TitleSettings(BaseModel): - main_title: str - sub_title: str + main_title: EscapedStr + sub_title: EscapedStr # ==================== 根路径 ==================== @@ -204,7 +250,15 @@ async def admin_login(login_data: AdminLogin): admin = cursor.fetchone() if not admin: raise HTTPException(status_code=401, detail='管理员用户名或密码错误') - return {'success': True, 'admin_id': admin['id'], 'username': admin['username']} + token = create_access_token( + {'id': admin['id'], 'username': admin['username'], 'role': 'admin'} + ) + return { + 'success': True, + 'admin_id': admin['id'], + 'username': admin['username'], + 'token': token, + } @app.get('/api/admin/check') @@ -254,9 +308,9 @@ async def get_title_settings(): } -@app.post('/api/settings/titles') +@app.post('/api/settings/titles', dependencies=[Depends(require_admin)]) async def update_title_settings(titles: TitleSettings): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( "UPDATE settings SET value = ? WHERE key = 'main_title'", @@ -290,9 +344,9 @@ async def get_award_settings(): } -@app.post('/api/settings/awards') +@app.post('/api/settings/awards', dependencies=[Depends(require_admin)]) async def update_award_settings(settings: AwardSettings): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( "UPDATE settings SET value = ? WHERE key = 'award_first'", @@ -309,9 +363,9 @@ async def update_award_settings(settings: AwardSettings): return {'success': True} -@app.post('/api/settings/award_names') +@app.post('/api/settings/award_names', dependencies=[Depends(require_admin)]) async def update_award_names(settings: AwardNamesSettings): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( "UPDATE settings SET value = ? WHERE key = 'award_first_name'", @@ -364,9 +418,9 @@ async def get_batches(): return batches -@app.post('/api/batches') +@app.post('/api/batches', dependencies=[Depends(require_admin)]) async def create_batch(batch: BatchCreate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( 'INSERT INTO batches (name, created_at) VALUES (?, ?)', @@ -376,35 +430,23 @@ async def create_batch(batch: BatchCreate): return {'success': True, 'id': new_id, 'name': batch.name} -@app.delete('/api/batches/{batch_id}') +@app.delete('/api/batches/{batch_id}', dependencies=[Depends(require_admin)]) async def delete_batch(batch_id: int): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT id FROM batches WHERE id = ?', (batch_id,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='批次不存在') - # 获取该批次所有节目序号 - cursor.execute('SELECT sn FROM programs WHERE batch_id = ?', (batch_id,)) - programs = cursor.fetchall() - for prog in programs: - cursor.execute('DELETE FROM scores WHERE program_sn = ?', (prog['sn'],)) - cursor.execute('DELETE FROM programs WHERE batch_id = ?', (batch_id,)) cursor.execute('DELETE FROM batches WHERE id = ?', (batch_id,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='批次不存在') return {'success': True} -@app.delete('/api/batches/{batch_id}/programs') +@app.delete('/api/batches/{batch_id}/programs', dependencies=[Depends(require_admin)]) async def clear_batch_programs(batch_id: int): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT id FROM batches WHERE id = ?', (batch_id,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='批次不存在') - cursor.execute('SELECT sn FROM programs WHERE batch_id = ?', (batch_id,)) - programs = cursor.fetchall() - for prog in programs: - cursor.execute('DELETE FROM scores WHERE program_sn = ?', (prog['sn'],)) cursor.execute('DELETE FROM programs WHERE batch_id = ?', (batch_id,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='批次不存在') return {'success': True} @@ -421,9 +463,9 @@ async def get_judges(): return judges -@app.post('/api/judges') +@app.post('/api/judges', dependencies=[Depends(require_admin)]) async def create_judge(judge: JudgeCreate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute('SELECT id FROM judges WHERE id = ?', (judge.id,)) if cursor.fetchone(): @@ -443,9 +485,9 @@ async def create_judge(judge: JudgeCreate): return {'success': True} -@app.put('/api/judges/{judge_id}') +@app.put('/api/judges/{judge_id}', dependencies=[Depends(require_admin)]) async def update_judge(judge_id: str, judge: JudgeUpdate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute('SELECT id FROM judges WHERE id = ?', (judge_id,)) if not cursor.fetchone(): @@ -456,15 +498,13 @@ async def update_judge(judge_id: str, judge: JudgeUpdate): return {'success': True} -@app.delete('/api/judges/{judge_id}') +@app.delete('/api/judges/{judge_id}', dependencies=[Depends(require_admin)]) async def delete_judge(judge_id: str): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT id FROM judges WHERE id = ?', (judge_id,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='评委不存在') - cursor.execute('DELETE FROM scores WHERE judge_id = ?', (judge_id,)) cursor.execute('DELETE FROM judges WHERE id = ?', (judge_id,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='评委不存在') return {'success': True} @@ -497,22 +537,16 @@ async def get_programs(batch_id: int | None = Query(None)): return programs -@app.post('/api/programs') +@app.post('/api/programs', dependencies=[Depends(require_admin)]) async def create_program(program: ProgramCreate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT sn FROM programs WHERE sn = ?', (program.sn,)) - if cursor.fetchone(): - raise HTTPException(status_code=400, detail='节目序号已存在') cursor.execute( - 'SELECT MAX(order_num) FROM programs WHERE batch_id = ?', - (program.batch_id,), - ) - max_order = cursor.fetchone()[0] - if max_order is None: - max_order = 0 - cursor.execute( - 'INSERT INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + """ + INSERT INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) + SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(order_num), 0) + 1, ? + FROM programs WHERE batch_id = ? + """, ( program.sn, program.name, @@ -520,10 +554,12 @@ async def create_program(program: ProgramCreate): program.performer, program.category, program.batch_id, - max_order + 1, datetime.now(), + program.batch_id, ), ) + if cursor.rowcount == 0: + raise HTTPException(status_code=400, detail='节目序号已存在') cursor.execute('SELECT id FROM judges') for judge in cursor.fetchall(): cursor.execute( @@ -533,43 +569,47 @@ async def create_program(program: ProgramCreate): return {'success': True} -@app.post('/api/programs/import') -async def import_programs(batch_id: int = Query(...), file: UploadFile = File(...)): +@app.post('/api/programs/import', dependencies=[Depends(require_admin)]) +async def import_programs( + request: Request, batch_id: int = Query(...), file: UploadFile = File(...) +): + MAX_MB = 10 + content_length = request.headers.get('content-length') + if content_length and int(content_length) > MAX_MB * 1024 * 1024: + raise HTTPException(status_code=413, detail=f'文件大小超过 {MAX_MB}MB 限制') try: contents = await file.read() df = pd.read_excel(BytesIO(contents)) - required_columns = ['节目序号', '节目名称', '演出单位', '表演者', '节目类别'] + required_columns = ['节目编号', '节目名称', '演出单位', '表演者', '节目类别'] for col in required_columns: if col not in df.columns: raise HTTPException(status_code=400, detail=f'Excel缺少必要列:{col}') - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( 'SELECT MAX(order_num) FROM programs WHERE batch_id = ?', (batch_id,) ) max_order_result = cursor.fetchone()[0] start_order = max_order_result if max_order_result is not None else 0 - - for idx, row in df.iterrows(): - sn = str(row['节目序号']).strip() - name = str(row['节目名称']).strip() - unit = str(row['演出单位']).strip() if pd.notna(row['演出单位']) else '' + order_counter = 0 + for _, row in df.iterrows(): + sn = escape_html(row['节目编号']) + name = escape_html(row['节目名称']) + unit = escape_html(row['演出单位']) if pd.notna(row['演出单位']) else '' performer = ( - str(row['表演者']).strip() if pd.notna(row['表演者']) else '' + escape_html(row['表演者']) if pd.notna(row['表演者']) else '' ) category = ( - str(row['节目类别']).strip() - if pd.notna(row['节目类别']) - else '舞蹈' + escape_html(row['节目类别']) if pd.notna(row['节目类别']) else '' ) if not sn or not name: continue - idx = cast(int, idx) - current_order = start_order + idx + 1 + order_counter += 1 + current_order = start_order + order_counter cursor.execute('SELECT sn FROM programs WHERE sn = ?', (sn,)) if cursor.fetchone(): cursor.execute( @@ -584,7 +624,7 @@ async def import_programs(batch_id: int = Query(...), file: UploadFile = File(.. ) else: cursor.execute( - 'INSERT INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + 'INSERT OR IGNORE INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', ( sn, name, @@ -604,13 +644,13 @@ async def import_programs(batch_id: int = Query(...), file: UploadFile = File(.. ) return {'success': True, 'message': f'成功导入/更新 {df.shape[0]} 个节目'} - except Exception as e: - raise HTTPException(status_code=400, detail=f'导入失败:{str(e)}') from e + except Exception as exc: + raise HTTPException(status_code=400, detail=f'导入失败:{str(exc)}') from exc -@app.put('/api/programs/{program_sn}') +@app.put('/api/programs/{program_sn}', dependencies=[Depends(require_admin)]) async def update_program(program_sn: str, program: ProgramUpdate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute('SELECT sn FROM programs WHERE sn = ?', (program_sn,)) if not cursor.fetchone(): @@ -629,15 +669,13 @@ async def update_program(program_sn: str, program: ProgramUpdate): return {'success': True} -@app.delete('/api/programs/{program_sn}') +@app.delete('/api/programs/{program_sn}', dependencies=[Depends(require_admin)]) async def delete_program(program_sn: str): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT sn FROM programs WHERE sn = ?', (program_sn,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='节目不存在') - cursor.execute('DELETE FROM scores WHERE program_sn = ?', (program_sn,)) cursor.execute('DELETE FROM programs WHERE sn = ?', (program_sn,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='节目不存在') return {'success': True} @@ -689,7 +727,7 @@ async def update_score(judge_id: str, score_data: ScoreDetailUpdate): 'art': 'art_score', 'overall': 'overall_score', } - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( f""" @@ -721,7 +759,7 @@ async def update_score(judge_id: str, score_data: ScoreDetailUpdate): @app.post('/api/comment/{judge_id}') async def update_comment(judge_id: str, comment_data: CommentUpdate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( 'INSERT INTO scores (judge_id, program_sn, comment, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(judge_id, program_sn) DO UPDATE SET comment = excluded.comment, updated_at = excluded.updated_at', @@ -730,7 +768,7 @@ async def update_comment(judge_id: str, comment_data: CommentUpdate): return {'success': True} -@app.post('/api/scores/admin/batch') +@app.post('/api/scores/admin/batch', dependencies=[Depends(require_admin)]) async def batch_update_scores(batch_data: ScoreBatchUpdate): """管理员批量更新总分""" with get_db() as conn: @@ -738,7 +776,12 @@ async def batch_update_scores(batch_data: ScoreBatchUpdate): for judge_id, total_score in batch_data.judge_scores.items(): if total_score is not None and (total_score < 0 or total_score > 100): raise HTTPException(status_code=400, detail='总分必须在0-100之间') - + cursor.execute('SELECT id FROM judges WHERE id = ?', (judge_id,)) + if not cursor.fetchone(): + raise HTTPException(status_code=404, detail=f'评委 {judge_id} 不存在') + with get_db(write=True) as conn: + cursor = conn.cursor() + for judge_id, total_score in batch_data.judge_scores.items(): if total_score is None: cursor.execute( """ @@ -920,7 +963,7 @@ async def export_excel(batch_id: int | None = Query(None)): data = [ { '名次': item['rank'], - '节目序号': item['sn'], + '节目编号': item['sn'], '节目名称': item['name'], '演出单位': item['unit'], '表演者': item['performer'], @@ -1064,12 +1107,12 @@ def render_print_program_template( html = f"""
节目序号: {program['sn']}
节目名称: {program['name']}
演出单位: {program['unit']}
表演者: {program['performer']}
节目类别: {program['category']}
节目编号: {program['sn']}
节目名称: {program['name']}
演出单位: {program['unit']}
表演者: {program['performer']}
节目类别: {program['category']}
| 评委姓名 | 总分(100分) | 评委点评 |
|---|---|---|
| {judge['name']} | {s.get('total') if s.get('total') > 0 else '-'} | {s.get('comment', '')} |
| {judge['name']} | {s.get('total') if s.get('total', 0) > 0 else '-'} | {s.get('comment', '')} |
评委组签名:____________________
日期:{datetime.now().strftime('%Y年%m月%d日')}
节目序号: {program['sn']} | 节目名称: {program['name']}
+节目编号: {program['sn']} | 节目名称: {program['name']}
演出单位: {program['unit']} | 表演者: {program['performer']} | 节目类别: {program['category']}
| 评分项目 | 满分 | 得分 | 评分要点 |
|---|
| 名次 | 节目序号 | 节目名称 | 演出单位 | 表演者 | 节目类别 | 平均分 | |||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 名次 | 节目编号 | 节目名称 | 演出单位 | 表演者 | 节目类别 | 平均分 |
| 名次 | 节目序号 | 节目名称 | 演出单位 | 表演者 | 类别 | 平均分 | 最高分 | 最低分 | 评委数 | 操作 |
|---|
| 名次 | 节目编号 | 节目名称 | 演出单位 | 表演者 | 类别 | 平均分 | 最高分 | 最低分 | 评委数 | 操作 |
|---|
序号:${prog.sn} | 单位:${escapeHtml(prog.unit)} | 表演者:${escapeHtml(prog.performer)} | 类别:${prog.category}
+编号:${prog.sn} | 单位:${prog.unit} | 表演者:${prog.performer} | 类别:${prog.category}
| 节目序号 | 节目名称 | 表演者 | '; + let html = '
|---|
| 节目编号 | 节目名称 | 表演者 | '; judgesData.forEach(j => { html += `${j.name} (${j.id}) | `; });
html += '操作 | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| ${prog.sn} | ${prog.name} | ${escapeHtml(prog.performer)}`; + html += ` | ||||||||||||||||
| ${prog.sn} | ${prog.name} | ${prog.performer}`;
for(let judge of judgesData){
let score = '';
const progScores = scoresMap[prog.sn];
@@ -1761,7 +1811,7 @@ HTML_TEMPLATE = """
try {
const res = await fetch('/api/scores/admin/batch', {
method:'POST',
- headers:{'Content-Type':'application/json'},
+ headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken},
body:JSON.stringify({program_sn:programSn, judge_scores:scores})
});
if(res.ok){
@@ -1868,7 +1918,7 @@ HTML_TEMPLATE = """
}
}
const firstCount = settings.first, secondCount = settings.second, thirdCount = settings.third;
- let html = '
|