Python Flask有意的空响应

问题:Python Flask有意的空响应

有没有一种方法可以返回make_response()具有特定属性的响应(来自对象或类似对象),以便它不会再次呈现页面并且也不会执行任何其他操作。我正在尝试在服务器上运行代码而不生成任何输出

一个简单的“不返回”会生成:

ValueError: View function did not return a response

这应该是可能的,因为以下内容仅下载文件而不渲染模板:

myString = "First line of a document"
response = make_response(myString)
response.headers["Content-Disposition"] = "attachment; filename=myFile.txt"
return response

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

回答 0

您回应的请求,HTTP服务器必须返回的东西。HTTP“空响应”响应为204 No Content

return ('', 204)

请注意,将文件返回到浏览器并不是一个空的响应,只是与HTML响应不同。

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.