How to get safe url for image in Flask? How to get safe url for image in Flask? flask flask

How to get safe url for image in Flask?


I see a couple of approaches

1) don't use predictable filenames, but save the file using some long random string instead and link it to the original filename in a database

2) make a custom route for static images, and only send the image if you verify the user has access:

@app.route('/send_file/<path:filename>')def send_file(filename):    image = Photo.query.filter_by(user_id=session['user_id'], filename=filename).first()    if  image:        return send_from_directory('image_folder', filename)    else:        return 'not allowed/found'

3 send the image as binary data in the JSON instead (more data + not elegant), see here.


If you have a session based user management system, create an authentication token (any random string / use bcrypt to generate encrypted tokens based on some session information) store it in your database / session.

For your images, do the following :

@app.route('/downloads/<auth_token>/<filename>')def downloads(auth_token, filename):    if session['auth_token'] == str(auth_token):        return send_from_directory(app.config['UPLOAD_FOLDER'], filename)    return 'You are not allowed to view this page'

The encrypted session tokens would be valid for a specific user for that specific session. If the auth_token does not match, the file would not be accessible on that url.