I am uploading file using flask rest-api and flask. As the file size is large I am using celery to upload the file on server. Below is the code.
Flask Rest API
@app.route('/upload',methods=['GET','POST'])
def upload():
file = request.files.get("file")
if not file:
return "some_error_msg"
elif file.filename == "":
return "some_error_msg"
if file:
filename = secure_filename(file.filename)
result = task_upload.apply_async(args=(filename, ABC, queue="upload")
return "some_task_id"
Celery task
@celery_app.task(bind=True)
def task_upload(self, filename: str, contents: Any) -> bool:
status = False
try:
status = save_file(filename, contents)
except exception as e:
print(f"Exception: {e}")
return status
Save method
def save_file(filename: str, contents: Any) -> bool:
file: Path = MEDIA_DIRPATH / filename
status: bool = False
# method-1 This code is using flask fileStorage, contents= is filestorage object
if contents:
contents.save(file)
status = True
# method-2 This code is using request.stream, contents= is IOBytes object
with open(file, "ab") as fp:
chunk = 4091
while True:
some code.
f.write(chunk)
status = True
return status
I am getting error while trying both methods
For Method-1, where I tried passing file variable(fileStorage type object) and getting error as
exc_info=(<class 'kombu.exceptions.EncodeError'>, EncodeError(TypeError('Object of type FileStorage is not JSON serializable'))
For Method-2, where I tried passing request.stream and getting error as
<gunicorn.http.body.Body object at some number>
TypeError: Object of type Body is not JSON serializable
How can I pass file(ABC) to celery task?
I am preferring method-1 but any will do. Please suggest.