Where do I get the 'environ' parameter for Werkzeug's send_file?

Viewed 971

Werkzeug 2.0 has a send_file method that Flask's send_file wraps.

One of its parameters is environ and its description is "(WSGIEnvironment) - The WSGI environ for the current request."

Where do I get this value to pass in my code?

from flask import Flask, request
from werkzeug.utils import send_file

app = Flask(__name__)

@app.route("/download/<string:filename>")
def download(filename):
    return send_file(filename, environ=...)
1 Answers

Since you're using Flask, use Flask's send_file, not Werkzeug's. Flask wraps Werkzeug's version to add Flask-specific behavior, including automatically passing the environ.

Also, with Flask or Werkzeug, do not use send_file to send arbitrary paths supplied by users, this is unsafe. Use send_from_directory to limit the top-level directory that the path can point to.

from flask import send_from_directory

@app.route("/download/<path:path>")
def download(path):
    return send_from_directory("uploads", path)

If you are using Werkzeug only, you either have the environ from the WSGI callable, or from the Request object with request.environ. Since Werkzeug doesn't have a request global like Flask does, you need to pass it manually to send_file.

from werkzeug import Request
from werkzeug.utils import send_from_directory

@Request.application
def app(request):
    return send_from_directory("uploads", request.path, environ=request.environ)
Related