Search code examples
pythonflaskstatic-fileseve

Python-Eve serve images


Good day! I have a REST API, which based on Python-Eve framework. I need to serve images, like simple Flask application (the reason is that doesn't need to run two servers). I'm move REST API to 'api' prefix and make simple function for serve static files:

from flask import send_from_directory
import eve

app = eve.Eve()

@app.route('/images/<path:path>')
def serve_static(path):
    return send_from_directory('images', path)

if __name__ == '__main__':
    app.run()

But it doesn't work and give me 404 error. When I replace send_from_directory for something simpler, like return "Hello" it works ok. Any idea how to implement it correctly? Thanks in advance.


Solution

  • I solve this problem wirh send_file function from flask package.

    This is my code:

    import os
    from flask import send_file, abort, request
    import eve
    
    from settings import BASE_DIR
    
    app = eve.Eve()
    
    
    @app.route('/images')
    def serve_images():
        if request.args.get('path'):
            path = os.path.join(BASE_DIR, 'app', 'images', request.args.get('path'))
        else:
            abort(403)
        return send_file(path)
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=8000)
    

    This aproach is very useful for me, because I can send files, which left outside flask application's folder.