Home > Enterprise >  how to send information(data) from a FastAPI server(client) to another FastAPI(model)
how to send information(data) from a FastAPI server(client) to another FastAPI(model)

Time:04-29

I am a newbie in RESTful API...

so I am trying to deploy two servers (client and model). The main idea is :

  • Client uploads his images on the client server, the client server(port 8000) will make some transformations
  • then I want the client server to make a post (with transformed data) to another server (also using FastAPI at port 8008).

Currently, I am strugling with the client server part, how to do a post to another server ?


# Define a flask app
app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="./templates")

origins = ["*"]
methods = ["*"]
headers = ["*"]


app.add_middleware(
    CORSMiddleware, 
    allow_origins = origins,
    allow_credentials = True,
    allow_methods = methods,
    allow_headers = headers    
)


@app.get('/', response_class=HTMLResponse)
def root(request: Request):
        return templates.TemplateResponse("index.html", {"request": request})
    #render_template('index.html')



#here the client will upload his image to the server
#and then encrypt it in the same button
@app.post('/encrypt', status_code=200)
async def upload_img(f: UploadFile = File(...)):

        ret = {}
        logger.debug(f)
        #base_path = "uploads"
        # filename = "predict.jpg"
        f.filename = "predict.jpg"
        base_path = os.path.dirname(__file__)
        file_path = os.path.join(base_path, 'uploads',secure_filename(f.filename))
        os.makedirs(base_path, exist_ok=True)
        try:
            with open(file_path, "wb") as buffer:
                shutil.copyfileobj(f.file, buffer)
        except Exception as e:
            print("Error: {}".format(str(e)))


        image_info = {"filename": f.filename,  "image": f}

        #preprocess image
        plain_input = load_input(f)
        #create a public context and drop sk
        ctx, sk = create_ctx()
        
        #encrypt 
        enc_input = prepare_input(ctx, plain_input)
        enc_input_serialize = enc_input.serialize()

        # la tu dois faire un post au serveur
        return  sk



class inference_param(BaseModel):
    context : bytes
    enc_input : bytes


@app.post("/data") #send data to the model server
async def send_data(data : inference_param):
    return data



CodePudding user response:

Since your endpoint is asynchronous you can use the asynchronous HTTP library like aiohttp or httpx to make the request.

If you don't want your clients of the client server to wait until the image is uploaded you can also use Background Tasks.

  • Related