Creating an upload service using FastAPI - cern automation
Jump to navigation
Jump to search
Setup VM prereqs
Ubuntu 2204 VM starting point
sudo apt update sudo apt install python3-pip sudo apt install python3-venv python3 -m venv fastapi-venv source fastapi-venv/bin/activate pip install fastapi uvicorn python-multipart pyyaml
Create the uploader app.py
ubuntu@fastapi-test-cern:~$ cat app.py
import time
import uvicorn
from fastapi import FastAPI,File,UploadFile
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "Whats up?"}
@app.post("/upload")
def upload_file(file: UploadFile = File(...)):
try:
contents = file.file.read()
with open(file.filename, 'wb') as f:
f.write(contents)
except Exception:
return {"message": "There was an error uploading the file"}
finally:
file.file.close()
return {"content": f"Uploaded {file.filename}"}
if __name__ == '__main__':
uvicorn.run(app,host="0.0.0.0",port=6443)
Run the app.py
ubuntu@fastapi-test-cern:~$ source fastapi-venv/bin/activate (fastapi-venv) ubuntu@fastapi-test-cern:~$ uvicorn app:app --reload
for this app we are using 0.0.0.0:6443 lets sort that now
ubuntu@fastapi-test-cern:~$ screen ubuntu@fastapi-test-cern:~$ source fastapi-venv/bin/activate (fastapi-venv) ubuntu@fastapi-test-cern:~$ uvicorn app:app --reload --host 0.0.0.0 --port 6443
Curl command to upload a file
curl -X 'POST' \ 'http://185.93.31.137:6443/upload' \ -H 'accept: application/json' \ -H 'Content-Type: multipart/form-data' \ -F 'file=@2_nodes-64-procs.pdf;type=application/pdf'