Python Flask 故意空响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24295426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:23:49  来源:igfitidea点击:

Python Flask Intentional Empty Response

pythonflaskresponse

提问by RukTech

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

有没有办法返回make_response()具有某些属性的响应(来自对象或类似的),这样它就不会再次呈现页面,也不做任何其他事情。我正在尝试在服务器上运行代码而不生成任何输出

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

采纳答案by Martijn Pieters

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

您正在响应请求,您的 HTTP 服务器必须返回某些内容。HTTP“空响应”响应是204 No Content

return ('', 204)

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

请注意,向浏览器返回文件不是空响应,只是与 HTML 响应不同。