-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
45 lines (36 loc) · 1.03 KB
/
api.py
File metadata and controls
45 lines (36 loc) · 1.03 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
38
39
40
41
42
43
44
45
from fastapi import FastAPI, UploadFile, File
import uvicorn
import tempfile
import os
from pydantic import BaseModel
import subprocess
import json
import utils
tmpdir = tempfile.mkdtemp()
app = FastAPI()
@app.post("/upload_file")
def hello(file: UploadFile = File(...)):
try:
# save file to tmpdir
with open(os.path.join(tmpdir, file.filename), "wb") as f:
f.write(file.file.read())
return "ok"
except Exception as e:
return {"error": str(e)}
class Cmd(BaseModel):
cmd: str
@app.post("/run")
def run_command(cmd: Cmd):
try:
# run command in tmpdir and return output
print(cmd.cmd)
cmd = subprocess.run(cmd.cmd, shell=True, cwd=tmpdir, capture_output=True)
return {
"stdout": cmd.stdout,
"stderr": cmd.stderr,
"returncode": cmd.returncode
}
except subprocess.CalledProcessError as e:
return {"error": utils.subprocess_error_to_json(e)}
def run():
uvicorn.run(app, host="0.0.0.0", port=2999)