Add batch management APIs, API security, rate limiting, and optimizations
- Batch device CRUD: POST /api/devices/batch (create 500), PUT /api/devices/batch (update 500), POST /api/devices/batch-delete (delete 100) with WHERE IN bulk queries - Batch command: POST /api/commands/batch with model_validator mutual exclusion - API key auth (X-API-Key header, secrets.compare_digest timing-safe) - Rate limiting via SlowAPIMiddleware (60/min default, 30/min writes) - Real client IP extraction (X-Forwarded-For / CF-Connecting-IP) - Global exception handler (no stack trace leaks, passes HTTPException through) - CORS with auto-disable credentials on wildcard origins - Schema validation: IMEI pattern, lat/lon ranges, Literal enums, MAC/UUID patterns - Heartbeats router, per-ID endpoints for locations/attendance/bluetooth - Input dedup in batch create, result ordering preserved - Baidu reverse geocoding, Gaode map tiles with WGS84→GCJ02 conversion - Device detail panel with feature toggles and command controls - Side panel for location/beacon pages with auto-select active device via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run>
This commit is contained in:
@@ -9,7 +9,7 @@ from sqlalchemy import func, select, or_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models import Device
|
||||
from app.schemas import DeviceCreate, DeviceUpdate
|
||||
from app.schemas import DeviceCreate, DeviceUpdate, BatchDeviceCreateItem
|
||||
|
||||
|
||||
async def get_devices(
|
||||
@@ -189,6 +189,103 @@ async def delete_device(db: AsyncSession, device_id: int) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
async def get_devices_by_ids(db: AsyncSession, device_ids: list[int]) -> list[Device]:
|
||||
"""Fetch multiple devices by IDs in a single query."""
|
||||
if not device_ids:
|
||||
return []
|
||||
result = await db.execute(select(Device).where(Device.id.in_(device_ids)))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_devices_by_imeis(db: AsyncSession, imeis: list[str]) -> list[Device]:
|
||||
"""Fetch multiple devices by IMEIs in a single query."""
|
||||
if not imeis:
|
||||
return []
|
||||
result = await db.execute(select(Device).where(Device.imei.in_(imeis)))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def batch_create_devices(
|
||||
db: AsyncSession, items: list[BatchDeviceCreateItem]
|
||||
) -> list[dict]:
|
||||
"""Batch create devices, skipping duplicates. Uses single query to check existing."""
|
||||
# One query to find all existing IMEIs
|
||||
imeis = [item.imei for item in items]
|
||||
existing_devices = await get_devices_by_imeis(db, imeis)
|
||||
existing_imeis = {d.imei for d in existing_devices}
|
||||
|
||||
results: list[dict] = [{} for _ in range(len(items))] # preserve input order
|
||||
new_device_indices: list[tuple[int, Device]] = []
|
||||
seen_imeis: set[str] = set()
|
||||
for i, item in enumerate(items):
|
||||
if item.imei in existing_imeis:
|
||||
results[i] = {"imei": item.imei, "success": False, "device_id": None, "error": f"IMEI {item.imei} already exists"}
|
||||
continue
|
||||
if item.imei in seen_imeis:
|
||||
results[i] = {"imei": item.imei, "success": False, "device_id": None, "error": "Duplicate IMEI in request"}
|
||||
continue
|
||||
seen_imeis.add(item.imei)
|
||||
device = Device(imei=item.imei, device_type=item.device_type, name=item.name)
|
||||
db.add(device)
|
||||
new_device_indices.append((i, device))
|
||||
|
||||
if new_device_indices:
|
||||
await db.flush()
|
||||
for idx, device in new_device_indices:
|
||||
await db.refresh(device)
|
||||
results[idx] = {"imei": device.imei, "success": True, "device_id": device.id, "error": None}
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def batch_update_devices(
|
||||
db: AsyncSession, device_ids: list[int], update_data: DeviceUpdate
|
||||
) -> list[dict]:
|
||||
"""Batch update devices with the same settings. Uses single query to fetch all."""
|
||||
devices = await get_devices_by_ids(db, device_ids)
|
||||
found_map = {d.id: d for d in devices}
|
||||
update_fields = update_data.model_dump(exclude_unset=True)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
results = []
|
||||
for device_id in device_ids:
|
||||
device = found_map.get(device_id)
|
||||
if device is None:
|
||||
results.append({"device_id": device_id, "success": False, "error": f"Device {device_id} not found"})
|
||||
continue
|
||||
for field, value in update_fields.items():
|
||||
setattr(device, field, value)
|
||||
device.updated_at = now
|
||||
results.append({"device_id": device_id, "success": True, "error": None})
|
||||
|
||||
if any(r["success"] for r in results):
|
||||
await db.flush()
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def batch_delete_devices(
|
||||
db: AsyncSession, device_ids: list[int]
|
||||
) -> list[dict]:
|
||||
"""Batch delete devices. Uses single query to fetch all."""
|
||||
devices = await get_devices_by_ids(db, device_ids)
|
||||
found_map = {d.id: d for d in devices}
|
||||
|
||||
results = []
|
||||
for device_id in device_ids:
|
||||
device = found_map.get(device_id)
|
||||
if device is None:
|
||||
results.append({"device_id": device_id, "success": False, "error": f"Device {device_id} not found"})
|
||||
continue
|
||||
await db.delete(device)
|
||||
results.append({"device_id": device_id, "success": True, "error": None})
|
||||
|
||||
if any(r["success"] for r in results):
|
||||
await db.flush()
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def get_device_stats(db: AsyncSession) -> dict:
|
||||
"""
|
||||
获取设备统计信息 / Get device statistics.
|
||||
|
||||
@@ -106,6 +106,7 @@ async def get_device_track(
|
||||
device_id: int,
|
||||
start_time: datetime,
|
||||
end_time: datetime,
|
||||
max_points: int = 10000,
|
||||
) -> list[LocationRecord]:
|
||||
"""
|
||||
获取设备轨迹 / Get device movement track within a time range.
|
||||
@@ -134,5 +135,6 @@ async def get_device_track(
|
||||
LocationRecord.recorded_at <= end_time,
|
||||
)
|
||||
.order_by(LocationRecord.recorded_at.asc())
|
||||
.limit(max_points)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
31
app/services/tcp_command_service.py
Normal file
31
app/services/tcp_command_service.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
TCP Command Service — Abstraction layer for sending commands to devices via TCP.
|
||||
|
||||
Breaks the circular import between routers/commands.py and tcp_server.py
|
||||
by lazily importing tcp_manager only when needed.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_tcp_manager():
|
||||
"""Lazily import tcp_manager to avoid circular imports."""
|
||||
from app.tcp_server import tcp_manager
|
||||
return tcp_manager
|
||||
|
||||
|
||||
def is_device_online(imei: str) -> bool:
|
||||
"""Check if a device is currently connected via TCP."""
|
||||
return imei in _get_tcp_manager().connections
|
||||
|
||||
|
||||
async def send_command(imei: str, command_type: str, command_content: str) -> bool:
|
||||
"""Send an online command (0x80) to a connected device."""
|
||||
return await _get_tcp_manager().send_command(imei, command_type, command_content)
|
||||
|
||||
|
||||
async def send_message(imei: str, message: str) -> bool:
|
||||
"""Send a text message (0x82) to a connected device."""
|
||||
return await _get_tcp_manager().send_message(imei, message)
|
||||
Reference in New Issue
Block a user