修复作业按次登记扣分上限误拦,节假日改用国内接口
1. 作业按次登记:单次扣分上限改为按"每次缺交"校验(一次缺交视为一次扣分), 不再因学生合计分值超过上限而整单拦截(解决班委提交时"扣分侧有问题") 2. 节假日接口:优先使用国内接口 api.jiejiariapi.com(放假/调休补班), 失败时自动降级到原备用接口;缓存、证书回退与手动校历逻辑不变
This commit is contained in:
1 parent
71c3263335
commit
250acf35fd
3 files changed
+68
-24
No files matched your search
@@ -9,7 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
"""节假日服务:在线获取法定节假日与调休补班数据(带缓存与失败降级)"""
|
"""节假日服务:优先使用国内接口获取法定节假日与调休补班(缓存 + 失败降级)"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import ssl
|
import ssl
|
||||||
@@ -24,7 +24,10 @@ from utils.logger import get_logger
|
|||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
HOLIDAY_API = 'https://timor.tech/api/holiday/year/{year}'
|
# 国内节假日接口(节假曰 API):{"YYYY-MM-DD": {"name": "...", "isOffDay": true/false}}
|
||||||
|
HOLIDAY_API_DOMESTIC = 'https://api.jiejiariapi.com/v1/holidays/{year}'
|
||||||
|
# 备用接口(timor.tech)
|
||||||
|
HOLIDAY_API_FALLBACK = 'https://timor.tech/api/holiday/year/{year}'
|
||||||
CACHE_TTL = 12 * 3600
|
CACHE_TTL = 12 * 3600
|
||||||
FAIL_CACHE_TTL = 600
|
FAIL_CACHE_TTL = 600
|
||||||
REQUEST_TIMEOUT = 6
|
REQUEST_TIMEOUT = 6
|
||||||
@@ -32,24 +35,50 @@ REQUEST_TIMEOUT = 6
|
|||||||
_cache: Dict[int, Dict[str, Any]] = {}
|
_cache: Dict[int, Dict[str, Any]] = {}
|
||||||
|
|
||||||
|
|
||||||
def _fetch_year_sync(year: int) -> Dict[str, Any]:
|
def _urlopen_json(url: str) -> Any:
|
||||||
"""同步请求节假日接口(在线程池中调用)"""
|
"""请求 JSON(证书校验失败时回退为不校验重试一次)"""
|
||||||
request = urllib.request.Request(
|
request = urllib.request.Request(
|
||||||
HOLIDAY_API.format(year=year),
|
url,
|
||||||
headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'}
|
headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'}
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
||||||
payload = json.loads(response.read().decode('utf-8'))
|
return json.loads(response.read().decode('utf-8'))
|
||||||
except (ssl.SSLError, urllib.error.URLError) as e:
|
except (ssl.SSLError, urllib.error.URLError) as e:
|
||||||
# 部分服务器根证书较旧,回退为不校验证书重试一次(节假日数据非敏感)
|
|
||||||
logger.warning(f"节假日接口证书校验失败,回退重试: {e}")
|
logger.warning(f"节假日接口证书校验失败,回退重试: {e}")
|
||||||
context = ssl._create_unverified_context()
|
context = ssl._create_unverified_context()
|
||||||
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT, context=context) as response:
|
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT, context=context) as response:
|
||||||
payload = json.loads(response.read().decode('utf-8'))
|
return json.loads(response.read().decode('utf-8'))
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_domestic(year: int) -> Dict[str, Any]:
|
||||||
|
"""国内接口:节假曰 API(放假 + 调休补班)"""
|
||||||
|
payload = _urlopen_json(HOLIDAY_API_DOMESTIC.format(year=year))
|
||||||
|
if not isinstance(payload, dict) or not payload:
|
||||||
|
raise ValueError("国内接口返回数据为空")
|
||||||
|
|
||||||
|
holidays: Dict[str, str] = {}
|
||||||
|
workdays: Dict[str, str] = {}
|
||||||
|
for key, info in payload.items():
|
||||||
|
if not isinstance(info, dict):
|
||||||
|
continue
|
||||||
|
day = str(info.get('date') or key)[:10]
|
||||||
|
name = info.get('name') or ('节假日' if info.get('isOffDay') else '调休补班')
|
||||||
|
if info.get('isOffDay'):
|
||||||
|
holidays[day] = name
|
||||||
|
else:
|
||||||
|
workdays[day] = name
|
||||||
|
|
||||||
|
if not holidays:
|
||||||
|
raise ValueError("国内接口未返回节假日数据")
|
||||||
|
return {'holidays': holidays, 'workdays': workdays, 'api_ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_timor(year: int) -> Dict[str, Any]:
|
||||||
|
"""备用接口:timor.tech"""
|
||||||
|
payload = _urlopen_json(HOLIDAY_API_FALLBACK.format(year=year))
|
||||||
if payload.get('code') != 0:
|
if payload.get('code') != 0:
|
||||||
raise ValueError(f"接口返回错误码: {payload.get('code')}")
|
raise ValueError(f"备用接口返回错误码: {payload.get('code')}")
|
||||||
|
|
||||||
holidays: Dict[str, str] = {}
|
holidays: Dict[str, str] = {}
|
||||||
workdays: Dict[str, str] = {}
|
workdays: Dict[str, str] = {}
|
||||||
@@ -63,6 +92,21 @@ def _fetch_year_sync(year: int) -> Dict[str, Any]:
|
|||||||
return {'holidays': holidays, 'workdays': workdays, 'api_ok': True}
|
return {'holidays': holidays, 'workdays': workdays, 'api_ok': True}
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_year_sync(year: int) -> Dict[str, Any]:
|
||||||
|
"""同步获取某年节假日数据:国内接口优先,失败后尝试备用接口"""
|
||||||
|
try:
|
||||||
|
return _fetch_domestic(year)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"国内节假日接口获取失败({year}),尝试备用接口: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _fetch_timor(year)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"备用节假日接口获取失败({year}): {e}")
|
||||||
|
|
||||||
|
return {'holidays': {}, 'workdays': {}, 'api_ok': False}
|
||||||
|
|
||||||
|
|
||||||
async def get_year_data(year: int) -> Dict[str, Any]:
|
async def get_year_data(year: int) -> Dict[str, Any]:
|
||||||
"""获取某年的节假日/调休数据(内存缓存,接口失败自动降级)"""
|
"""获取某年的节假日/调休数据(内存缓存,接口失败自动降级)"""
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -77,12 +121,15 @@ async def get_year_data(year: int) -> Dict[str, Any]:
|
|||||||
data = await loop.run_in_executor(None, _fetch_year_sync, year)
|
data = await loop.run_in_executor(None, _fetch_year_sync, year)
|
||||||
data['fetched_at'] = now
|
data['fetched_at'] = now
|
||||||
_cache[year] = data
|
_cache[year] = data
|
||||||
logger.info(
|
if data['api_ok']:
|
||||||
f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天"
|
logger.info(
|
||||||
)
|
f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.warning(f"节假日数据获取失败: {year}年(接口均不可用)")
|
||||||
return data
|
return data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"节假日接口获取失败({year}): {e}")
|
logger.warning(f"节假日数据获取异常({year}): {e}")
|
||||||
failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now}
|
failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now}
|
||||||
_cache[year] = failed
|
_cache[year] = failed
|
||||||
return failed
|
return failed
|
||||||
|
|||||||
@@ -84,15 +84,12 @@ class HomeworkService:
|
|||||||
if sid not in student_map:
|
if sid not in student_map:
|
||||||
return {"success": False, "message": "存在无效学生(不存在或已禁用)"}
|
return {"success": False, "message": "存在无效学生(不存在或已禁用)"}
|
||||||
|
|
||||||
if limits["max_subtract"] is not None:
|
# 单次扣分上限按"每次缺交"校验:按次登记中一次缺交视为一次扣分,合计分可超过单次上限
|
||||||
for sid, miss in miss_map.items():
|
if limits["max_subtract"] is not None and deduction > limits["max_subtract"]:
|
||||||
total_deduct = miss * deduction
|
return {
|
||||||
if total_deduct > limits["max_subtract"]:
|
"success": False,
|
||||||
name = student_map[sid]["name"]
|
"message": f"单次缺交扣分不能超过{limits['max_subtract']}分"
|
||||||
return {
|
}
|
||||||
"success": False,
|
|
||||||
"message": f"{name} 缺交{miss}次合计扣{total_deduct}分,超过单次扣分上限{limits['max_subtract']}分"
|
|
||||||
}
|
|
||||||
|
|
||||||
# 创建作业记录(每次一条)
|
# 创建作业记录(每次一条)
|
||||||
base_title = (title or "作业登记").strip() or "作业登记"
|
base_title = (title or "作业登记").strip() or "作业登记"
|
||||||
|
|||||||
+2
-2
@@ -174,7 +174,7 @@
|
|||||||
3. 点击"开始补全",完成后提示:上课日数量、新增条数、跳过已有条数
|
3. 点击"开始补全",完成后提示:上课日数量、新增条数、跳过已有条数
|
||||||
|
|
||||||
规则说明:
|
规则说明:
|
||||||
- **跳过周末与法定节假日**(节假日/调休补班来自在线接口)
|
- **跳过周末与法定节假日**(节假日/调休补班来自国内在线接口,失败时自动切换备用接口)
|
||||||
- **调休补班日照常**(接口中的补班日按上课处理)
|
- **调休补班日照常**(接口中的补班日按上课处理)
|
||||||
- **手动补课日照常**;手动放假日跳过
|
- **手动补课日照常**;手动放假日跳过
|
||||||
- 已有的考勤记录(含缺勤/迟到/请假)**不会被覆盖**
|
- 已有的考勤记录(含缺勤/迟到/请假)**不会被覆盖**
|
||||||
@@ -183,7 +183,7 @@
|
|||||||
#### 节假日 / 补课设置
|
#### 节假日 / 补课设置
|
||||||
点击工具栏"节假日/补课"按钮打开校历设置:
|
点击工具栏"节假日/补课"按钮打开校历设置:
|
||||||
|
|
||||||
- **查询范围**:查看范围内的法定节假日(放假)、调休补班(按上课)——来自在线接口,只读
|
- **查询范围**:查看范围内的法定节假日(放假)、调休补班(按上课)——来自国内在线接口(失败时自动切换备用接口),只读
|
||||||
- **手动添加**:添加学校自己的安排,可选择"补课(按上课)"或"放假(按休息)",可填写备注;手动设置**优先于接口**(例如把某天调休补班改回放假)
|
- **手动添加**:添加学校自己的安排,可选择"补课(按上课)"或"放假(按休息)",可填写备注;手动设置**优先于接口**(例如把某天调休补班改回放假)
|
||||||
- 手动添加的记录可随时删除
|
- 手动添加的记录可随时删除
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user