135

Is there a way to return a response (from make_response() object or similar) with certain properties so that it doesn't render the page again and doesn't do anything else either. I am trying to run a code on the server without generating any output

A simple 'return None' produces:

ValueError: View function did not return a response

This should be possible because the following only downloads a file and doesn't render the template:

myString = "First line of a document"
response = make_response(myString)
response.headers["Content-Disposition"] = "attachment; filename=myFile.txt"
return response
Mel
  • 5,837
  • 10
  • 37
  • 42
RukTech
  • 5,065
  • 5
  • 22
  • 23

2 Answers2

236

You are responding to a request, your HTTP server must return something. The HTTP 'empty response' response is 204 No Content:

return ('', 204)

Note that returning a file to the browser is not an empty response, just different from a HTML response.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 22
    Ftr: you may use `httplib.NO_CONTENT` to avoid the magic number. – dtk Feb 14 '16 at 00:23
  • 23
    Note the equivalent of Python 2’s `httplib.NO_CONTENT` in Python 3 is `http.HTTPStatus.NO_CONTENT`. – bfontaine Sep 20 '17 at 14:21
  • 3
    @bfontaine: or `http.client.NO_CONTENT` – Martijn Pieters Sep 20 '17 at 14:38
  • 3
    @bfontaine: at the bottom of the [`http` package docs](https://docs.python.org/3/library/http.html); these *used* to be the normal location until the `HTTPStatus` enum was introduced, see https://github.com/python/cpython/commit/e4db76967d7fb0ec0f5a98a9603ca5563f4a8320 – Martijn Pieters Sep 21 '17 at 15:13
12

Use Flask Response

with status 204 (no content)

from flask import Response

return Response(status=204)
imbr
  • 6,226
  • 4
  • 53
  • 65