UnisKB/apps/system_manage/ai_hub_service_api.py

105 lines
5.1 KiB
Python

import copy
import json
import re
from django.db import transaction
from rest_framework.exceptions import ValidationError
from system_manage.models import SystemSetting
SETTING = 11029
DEFAULT = {'method': 'POST', 'parameters': [
{'name': 'markdown', 'target': 'markdown', 'type': 'string', 'required': False},
{'name': 'name', 'target': 'name', 'type': 'string', 'required': False},
{'name': 'file', 'target': 'file', 'type': 'file', 'required': False},
]}
NAME = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,63}$')
def validate(config):
if not isinstance(config, dict) or set(config) != {'method', 'parameters'} or config['method'] not in ('GET', 'POST') or not isinstance(config['parameters'], list):
raise ValidationError('服务接口配置无效')
names, targets = set(), set()
for p in config['parameters']:
if not isinstance(p, dict) or set(p) != {'name', 'target', 'type', 'required'}:
raise ValidationError('服务参数配置无效')
name, target = p['name'], p['target']
if not isinstance(name, str) or not isinstance(target, str) or not NAME.fullmatch(name) or name.lower() in ('data', '__proto__', 'constructor', 'prototype') or name in names or target in targets:
raise ValidationError('服务参数名称重复或无效')
if target not in ('markdown', 'name', 'file') or p['type'] != ('file' if target == 'file' else 'string') or not isinstance(p['required'], bool):
raise ValidationError('服务参数类型无效')
if config['method'] == 'GET' and target == 'file':
raise ValidationError('GET 不支持文件参数')
names.add(name); targets.add(target)
return copy.deepcopy(config)
def get_config(service_id):
meta = SystemSetting.objects.filter(pk=SETTING).values_list('meta', flat=True).first() or {}
return copy.deepcopy(meta.get('services', {}).get(str(service_id), DEFAULT))
def save_config(service_id, config=None):
with transaction.atomic():
row, _ = SystemSetting.objects.get_or_create(type=SETTING, defaults={'meta': {'services': {}}})
row = SystemSetting.objects.select_for_update().get(pk=row.pk)
meta = dict(row.meta or {}); services = dict(meta.get('services', {}))
if config is None:
services.pop(str(service_id), None)
else:
services[str(service_id)] = validate(config)
meta['services'] = services; row.meta = meta; row.save(update_fields=['meta'])
def parse_request(request, config):
if request.method != config['method']:
raise ValidationError('请求方法与服务配置不一致')
if request.method == 'GET':
if len(request.META.get('QUERY_STRING', '')) > 8192:
raise ValidationError('请求参数过长')
source = request.query_params
elif 'data' in request.data:
if hasattr(request.data, 'getlist') and len(request.data.getlist('data')) != 1:
raise ValidationError('参数不能重复')
try:
source = json.loads(request.data['data'])
except (ValueError, TypeError):
raise ValidationError('任务参数无效')
if not isinstance(source, dict) or set(request.data) - {'data', *request.FILES.keys()}:
raise ValidationError('任务参数无效')
else:
source = request.data
if not isinstance(source, dict):
raise ValidationError('任务参数无效')
params = config['parameters']; names = {p['name'] for p in params}
legacy_priority = request.method == 'POST' and config == DEFAULT
if legacy_priority:
names.add('priority')
if set(source) - names or set(request.FILES) - names:
raise ValidationError('包含未知参数')
output = {}; upload = None
if legacy_priority and 'priority' in source:
priority = source.get('priority')
if hasattr(source, 'getlist') and len(source.getlist('priority')) > 1:
raise ValidationError('参数不能重复')
if isinstance(priority, bool) or not isinstance(priority, int) or not 0 <= priority <= 9:
raise ValidationError('优先级无效')
output['priority'] = priority
for p in params:
name = p['name']
if hasattr(request.FILES, 'getlist') and len(request.FILES.getlist(name)) > 1:
raise ValidationError('参数不能重复')
if hasattr(source, 'getlist') and len(source.getlist(name)) > 1:
raise ValidationError('参数不能重复')
value = request.FILES.get(name) if p['type'] == 'file' else source.get(name)
if p['type'] == 'file' and name in source and name not in request.FILES:
raise ValidationError('文件参数无效')
if p['type'] != 'file' and name in request.FILES:
raise ValidationError('参数类型无效')
if value is None or value == '':
if p['required']: raise ValidationError('缺少必填参数')
continue
if p['type'] == 'file': upload = value
elif not isinstance(value, str): raise ValidationError('参数类型无效')
else: output[p['target']] = value
return output, upload