|
import os |
|
import pickle |
|
from fastapi import FastAPI, File, UploadFile, HTTPException |
|
from fastapi.responses import StreamingResponse |
|
from io import BytesIO |
|
import subprocess |
|
|
|
app = FastAPI() |
|
|
|
@app.post("/container_task") |
|
async def container_task(file: UploadFile = File(...)): |
|
|
|
input_filepath = "input.pkl" |
|
with open(input_filepath, "wb") as f: |
|
f.write(await file.read()) |
|
|
|
|
|
try: |
|
with open(input_filepath, 'rb') as f: |
|
unpickle_param = pickle.load(f) |
|
except Exception as e: |
|
raise HTTPException(status_code=400, detail=f"Failed to unpickle the input file: {str(e)}") |
|
|
|
|
|
command = ["docker", "run", "--rm", "bbdown", str(unpickle_param)] |
|
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
|
|
|
|
|
stdout_stream = BytesIO() |
|
stderr_stream = BytesIO() |
|
|
|
|
|
def stream_output(): |
|
while True: |
|
output = process.stdout.readline() |
|
if output == b"" and process.poll() is not None: |
|
break |
|
if output: |
|
stdout_stream.write(output) |
|
|
|
stderr_output = process.stderr.read() |
|
stderr_stream.write(stderr_output) |
|
yield "" |
|
|
|
|
|
async def response_stream(): |
|
for _ in stream_output(): |
|
yield stdout_stream.getvalue() |
|
stdout_stream.seek(0) |
|
stdout_stream.truncate() |
|
|
|
|
|
process.wait() |
|
|
|
|
|
if process.returncode != 0: |
|
raise HTTPException(status_code=500, detail=f"Docker command failed with error: {stderr_stream.getvalue().decode()}") |
|
|
|
|
|
output_filepath = "output.pkl" |
|
with open(output_filepath, 'wb') as f: |
|
f.write(b"Your output data here.") |
|
|
|
|
|
return StreamingResponse(open(output_filepath, "rb"), media_type='application/octet-stream', |
|
headers={"Content-Disposition": f"attachment; filename={os.path.basename(output_filepath)}"}) |
|
|
|
|
|
from fastapi import FastAPI |
|
from fastapi.responses import StreamingResponse |
|
import time |
|
import asyncio |
|
|
|
app = FastAPI() |
|
|
|
async def stream_generator(): |
|
for i in range(10): |
|
yield f"Data chunk {i}\n" |
|
await asyncio.sleep(1) |
|
|
|
@app.get("/stream") |
|
async def stream_response(): |
|
return StreamingResponse(stream_generator(), media_type="text/plain") |
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run(app, host="127.0.0.1", port=8000) |
|
|
|
|
|
def client_call(*args, **kwargs): |
|
|
|
result = execute(*args, **kwargs) |
|
|
|
result.text |
|
result.file_manifest |
|
result.files |
|
|
|
|