Implement OCR API Using FastAPI - 2

Learn to create a REST API that performs OCR on multiple images concurrently using FastAPI.

Save images to the server

Let’s now create a function that accepts your image, the path of the directory on the server where you want to store the image, and the name of the saved image. We can name this function _save_file_to_server().

Press + to interact
import shutil
import os
def _save_file_to_server(uploaded_file, path=".", save_as="default"):
extension = os.path.splitext(uploaded_file.filename)[-1]
temp_file = os.path.join(path, save_as + extension)
with open(temp_file, "wb") as buffer:
shutil.copyfileobj(uploaded_file.file, buffer)
return temp_file

Explanation

  • On line 1, we import the required packages.

  • On line 3, we define our function and also assign the default values to the path parameter and the save_as parameter, which is the name of the image while saving on the server.

  • On line 5, we try to find out the extension of the uploaded file. In our case, it can be png, jpg, or any other image format.

  • On line 6, we create the image path using the os module.

  • On lines 8 and 9 ...