19

I am using Flask (based on Werkzeug) which uses Python.

The user can download a file, I'm using the send_from_directory-function.

However when actually downloading the file, the HTTP header content-length is not set. So the user has no idea how big the file being downloaded is.

I can use os.path.getsize(FILE_LOCATION) in Python to get the file size (in bytes), but cannot find a way to set the content-length header in Flask.

Any ideas?

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
Jon Cox
  • 10,622
  • 22
  • 78
  • 123

3 Answers3

40

I needed this also, but for every requests, so here's what I did (based on the doc) :

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41
Cyril N.
  • 38,875
  • 36
  • 142
  • 243
39

Since version 0.6 the canonical way to add headers to a response object is via the make_response method (see Flask docs).

def index():
    response = make_response(render_template('index.html', foo=42))
    response.headers['X-Parachutes'] = 'parachutes are cool'
    return response
raben
  • 3,060
  • 5
  • 32
  • 34
15

I believe you'd do something like this (untested):

from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))

See: Werkzug's Headers object and Flask's Response object.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293