-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_server.py
More file actions
37 lines (34 loc) · 1.24 KB
/
test_server.py
File metadata and controls
37 lines (34 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from fastapi import FastAPI, HTTPException
import subprocess
import os
app = FastAPI()
@app.get("/")
async def execute_curl():
"""
Executes the predefined curl command and returns the output.
"""
try:
# Run the curl command
result = subprocess.run(
["curl", "-X", "GET", f"{os.getenv('ESP_IP')}/json/devices/"],
capture_output=True, # Captures stdout and stderr
text=True, # Returns strings instead of bytes
check=True # Raises CalledProcessError if the exit code is non-zero
)
# Return the output of the curl command
return {
"status": "success",
"output": result.stdout.strip()
}
except subprocess.CalledProcessError as e:
# Handles errors if the curl command itself fails (e.g., bad URL, connection refused)
raise HTTPException(
status_code=500,
detail={"error": "Curl command failed", "stderr": e.stderr.strip()}
)
except Exception as e:
# Handles any other unexpected Python errors
raise HTTPException(
status_code=500,
detail={"error": "An unexpected error occurred", "message": str(e)}
)