Skip to content

Commit 78150a4

Browse files
committed
refactor: Clean up imports and improve code readability
- Removed unused imports across multiple files, including asyncio and json. - Simplified conditional expressions for better clarity in lifespan and execution contexts. - Adjusted type hints and default values in models for consistency. - Enhanced formatting of long strings for improved readability in configuration files.
1 parent ba516ec commit 78150a4

30 files changed

Lines changed: 124 additions & 133 deletions

src/api/dashboard_metrics.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Dashboard metrics API endpoints for advanced analytics."""
22

33
from datetime import datetime, timedelta, timezone
4-
from typing import Any, Dict, List, Literal, Optional
4+
from typing import Dict, List, Literal, Optional
55

66
from fastapi import APIRouter, Depends, Header, HTTPException, Query
77
from pydantic import BaseModel

src/api/exec.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,6 @@
99

1010
from ..models import ExecRequest, ExecResponse
1111
from ..services.orchestrator import ExecutionOrchestrator
12-
from ..services.interfaces import (
13-
SessionServiceInterface,
14-
ExecutionServiceInterface,
15-
FileServiceInterface,
16-
)
1712
from ..dependencies.services import (
1813
SessionServiceDep,
1914
FileServiceDep,

src/api/files.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,18 @@
33
# Standard library imports
44
from datetime import datetime, timezone
55
from pathlib import Path
6-
from typing import List, Optional, Union
6+
from typing import List, Optional
77
from urllib.parse import quote
88

99
# Third-party imports
1010
import structlog
11-
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File, Form, Query
11+
from fastapi import APIRouter, HTTPException, UploadFile, File, Form, Query
1212
from fastapi.responses import Response, StreamingResponse
1313
from unidecode import unidecode
1414

1515
# Local application imports
1616
from ..config import settings
1717
from ..dependencies import FileServiceDep
18-
from ..models import (
19-
FileUploadRequest,
20-
FileUploadResponse,
21-
FileInfo,
22-
FileListResponse,
23-
FileDownloadResponse,
24-
FileDeleteResponse,
25-
)
26-
from ..services.interfaces import FileServiceInterface
2718
from ..utils.id_generator import generate_session_id
2819

2920

src/api/health.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Health check and monitoring endpoints."""
22

3-
from typing import Dict, Any
43
from fastapi import APIRouter, HTTPException, Depends, Query
54
from fastapi.responses import JSONResponse
65
import structlog
@@ -42,11 +41,11 @@ async def detailed_health_check(
4241
# Prepare response
4342
response_data = {
4443
"status": overall_status.value,
45-
"timestamp": service_results[
46-
list(service_results.keys())[0]
47-
].timestamp.isoformat()
48-
if service_results
49-
else None,
44+
"timestamp": (
45+
service_results[list(service_results.keys())[0]].timestamp.isoformat()
46+
if service_results
47+
else None
48+
),
5049
"services": {
5150
name: result.to_dict() for name, result in service_results.items()
5251
},

src/config/languages.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ class LanguageConfig:
5959
image="code-interpreter/nodejs:latest",
6060
user_id=1001,
6161
file_extension="ts",
62-
execution_command="tsc /mnt/data/code.ts --outDir /mnt/data --module commonjs --target ES2019 && node /mnt/data/code.js",
62+
execution_command="tsc /mnt/data/code.ts --outDir /mnt/data --module commonjs "
63+
"--target ES2019 && node /mnt/data/code.js",
6364
uses_stdin=False,
6465
timeout_multiplier=1.2,
6566
memory_multiplier=1.0,

src/dependencies/services.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
# Standard library imports
44
from functools import lru_cache
5-
from typing import Annotated, Optional
5+
from typing import Annotated
66

77
# Third-party imports
8-
from fastapi import Depends, Request
8+
from fastapi import Depends
99
import structlog
1010

1111
# Local application imports

src/main.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
"""Main FastAPI application for the Code Interpreter API."""
22

33
# Standard library imports
4-
import asyncio
5-
import os
64
import sys
75
from contextlib import asynccontextmanager
86

@@ -121,9 +119,9 @@ async def lifespan(app: FastAPI):
121119
cleanup_scheduler.set_services(
122120
execution_service=get_execution_service(),
123121
file_service=get_file_service(),
124-
state_archival_service=get_state_archival_service()
125-
if settings.state_archive_enabled
126-
else None,
122+
state_archival_service=(
123+
get_state_archival_service() if settings.state_archive_enabled else None
124+
),
127125
)
128126
cleanup_scheduler.start()
129127
logger.info(

src/middleware/security.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
# Standard library imports
44
import time
5-
from typing import Callable, Dict, Any, Optional
5+
from typing import Callable, Optional
66

77
# Third-party imports
88
import structlog
@@ -152,8 +152,6 @@ def _should_skip_auth(self, request: Request) -> bool:
152152

153153
async def _authenticate_request(self, request: Request, scope: dict):
154154
"""Handle API key authentication with rate limiting."""
155-
import hashlib
156-
157155
# Extract API key
158156
api_key = self._extract_api_key(request)
159157

src/models/api_key.py

Lines changed: 57 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import json
44
from dataclasses import dataclass, field
5-
from datetime import datetime, timezone
5+
from datetime import datetime
66
from typing import Optional, Dict, Any
77

88

@@ -76,21 +76,31 @@ def to_redis_hash(self) -> Dict[str, str]:
7676
"name": self.name,
7777
"created_at": self.created_at.isoformat(),
7878
"enabled": "true" if self.enabled else "false",
79-
"rate_limits_per_second": str(self.rate_limits.per_second)
80-
if self.rate_limits.per_second is not None
81-
else "",
82-
"rate_limits_per_minute": str(self.rate_limits.per_minute)
83-
if self.rate_limits.per_minute is not None
84-
else "",
85-
"rate_limits_hourly": str(self.rate_limits.hourly)
86-
if self.rate_limits.hourly is not None
87-
else "",
88-
"rate_limits_daily": str(self.rate_limits.daily)
89-
if self.rate_limits.daily is not None
90-
else "",
91-
"rate_limits_monthly": str(self.rate_limits.monthly)
92-
if self.rate_limits.monthly is not None
93-
else "",
79+
"rate_limits_per_second": (
80+
str(self.rate_limits.per_second)
81+
if self.rate_limits.per_second is not None
82+
else ""
83+
),
84+
"rate_limits_per_minute": (
85+
str(self.rate_limits.per_minute)
86+
if self.rate_limits.per_minute is not None
87+
else ""
88+
),
89+
"rate_limits_hourly": (
90+
str(self.rate_limits.hourly)
91+
if self.rate_limits.hourly is not None
92+
else ""
93+
),
94+
"rate_limits_daily": (
95+
str(self.rate_limits.daily)
96+
if self.rate_limits.daily is not None
97+
else ""
98+
),
99+
"rate_limits_monthly": (
100+
str(self.rate_limits.monthly)
101+
if self.rate_limits.monthly is not None
102+
else ""
103+
),
94104
"metadata": json.dumps(self.metadata),
95105
"last_used_at": self.last_used_at.isoformat() if self.last_used_at else "",
96106
"usage_count": str(self.usage_count),
@@ -101,31 +111,39 @@ def from_redis_hash(cls, data: Dict[bytes, bytes]) -> "ApiKeyRecord":
101111
"""Create from Redis hash data (bytes keys/values)."""
102112
# Decode bytes to strings
103113
decoded = {
104-
k.decode()
105-
if isinstance(k, bytes)
106-
else k: v.decode()
107-
if isinstance(v, bytes)
108-
else v
114+
k.decode() if isinstance(k, bytes) else k: (
115+
v.decode() if isinstance(v, bytes) else v
116+
)
109117
for k, v in data.items()
110118
}
111119

112120
# Parse rate limits
113121
rate_limits = RateLimits(
114-
per_second=int(decoded["rate_limits_per_second"])
115-
if decoded.get("rate_limits_per_second")
116-
else None,
117-
per_minute=int(decoded["rate_limits_per_minute"])
118-
if decoded.get("rate_limits_per_minute")
119-
else None,
120-
hourly=int(decoded["rate_limits_hourly"])
121-
if decoded.get("rate_limits_hourly")
122-
else None,
123-
daily=int(decoded["rate_limits_daily"])
124-
if decoded.get("rate_limits_daily")
125-
else None,
126-
monthly=int(decoded["rate_limits_monthly"])
127-
if decoded.get("rate_limits_monthly")
128-
else None,
122+
per_second=(
123+
int(decoded["rate_limits_per_second"])
124+
if decoded.get("rate_limits_per_second")
125+
else None
126+
),
127+
per_minute=(
128+
int(decoded["rate_limits_per_minute"])
129+
if decoded.get("rate_limits_per_minute")
130+
else None
131+
),
132+
hourly=(
133+
int(decoded["rate_limits_hourly"])
134+
if decoded.get("rate_limits_hourly")
135+
else None
136+
),
137+
daily=(
138+
int(decoded["rate_limits_daily"])
139+
if decoded.get("rate_limits_daily")
140+
else None
141+
),
142+
monthly=(
143+
int(decoded["rate_limits_monthly"])
144+
if decoded.get("rate_limits_monthly")
145+
else None
146+
),
129147
)
130148

131149
# Parse timestamps
@@ -158,9 +176,9 @@ def to_display_dict(self) -> Dict[str, Any]:
158176
"name": self.name,
159177
"enabled": self.enabled,
160178
"created_at": self.created_at.isoformat(),
161-
"last_used_at": self.last_used_at.isoformat()
162-
if self.last_used_at
163-
else None,
179+
"last_used_at": (
180+
self.last_used_at.isoformat() if self.last_used_at else None
181+
),
164182
"usage_count": self.usage_count,
165183
"rate_limits": {
166184
"hourly": self.rate_limits.hourly,

src/models/errors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Error models and exception classes for the Code Interpreter API."""
22

33
import time
4-
from typing import Optional, Dict, Any, List
4+
from typing import Optional, List
55
from pydantic import BaseModel, Field
66
from enum import Enum
77

0 commit comments

Comments
 (0)