weppy-REST
weppy-REST copied to clipboard
api with file management
Hi @gi0baro What would be the best way to work with models with 'upload' type fields? How do I handle the post? Base64?
Jose
I usually create a separate endpoint for the file upload and store only a filename in the model. It is usually not the best idea to store files in the database.
In weppy it can be done this way:
@app.route("/file-upload")
def file_upload():
fileitem = request.params['file']
if isinstance(fileitem, FieldStorage) and fileitem.filename:
filename = os.path.basename(fileitem.filename)
filepath = f'media/{filename}'
while os.path.isfile(filepath): # if file exist don't override it, use different filename
filename = generate_unique_filename(filename)
filepath = f'media/{filename}'
open(filepath, 'wb').write(fileitem.file.read())
return filename
else:
return "error!"
I am not saving filename to model here, but it can be done easily.