Files
altium-render-engine/backend/app/uploads.py
T
2026-11-09 12:34:50 +03:30

39 خطوط
1.7 KiB
Python

"""Shared bounded native schematic upload validation."""
from fastapi import HTTPException
from .config import settings
from .parser.record_decoder import ParseError,detect_format
async def read_native(file, document_type):
try:
name=(file.filename or '').replace('\\','/').rsplit('/',1)[-1]
name=''.join(c for c in name if c.isprintable())[:255]
suffix = '.PcbDoc' if document_type == 'pcb' else '.SchDoc'
if not name.lower().endswith(suffix.lower()):
raise HTTPException(415,{'code':'unsupported_file_type','message':f'Upload a {suffix} file'})
body=bytearray()
while chunk:=await file.read(1024*1024):
body.extend(chunk)
if len(body)>settings().max_upload_bytes:
raise HTTPException(413,{'code':'upload_too_large','message':'Schematic exceeds configured upload size'})
from starlette.concurrency import run_in_threadpool
from .parser.pcb_container import identify_pcb, contains_pcb
try:
if document_type == 'pcb':
await run_in_threadpool(identify_pcb, bytes(body))
else:
detect_format(bytes(body))
if await run_in_threadpool(contains_pcb, bytes(body)):
raise ParseError('PCB files are not accepted by schematic endpoints')
except ParseError as exc:
raise HTTPException(422,{'code':'invalid_pcb' if document_type == 'pcb' else 'invalid_schematic','message':str(exc)}) from exc
return name,bytes(body)
finally:await file.close()
async def read_schematic(file):
return await read_native(file, "schematic")
async def read_pcb(file):
return await read_native(file, "pcb")