weppy-REST icon indicating copy to clipboard operation
weppy-REST copied to clipboard

api with file management

Open josejachuf opened this issue 7 years ago • 1 comments

Hi @gi0baro What would be the best way to work with models with 'upload' type fields? How do I handle the post? Base64?

Jose

josejachuf avatar Sep 27 '17 23:09 josejachuf

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.

guy881 avatar Jan 13 '18 19:01 guy881