python - 发送不改变用户当前页面的 HTTP 响应

标签 python flask httpresponse wsgi

我有一个 JavaScript 小书签,当用户在其他页面(即不在我的服务器上)时,它可以将信息发布到(Flask 驱动的)服务器。我不想通过我的服务器响应劫持他们的 session 来中断用户的浏览。

我最初的想法是我可以通过某种方式抑制来自 Flask 的 HTTP 响应;防止它向客户端发送任何东西,这样它们就不会被神秘地重定向。我希望我可以通过从 View 返回 null 来做到这一点。

然后我想这可能是一些让客户端知道信息已成功提交的 HTTP 响应,但会让客户端留在当前页面上。假设标题值类似于“这是您请求的结果,但您不应更改当前显示”?

最佳答案

要回答您修改后的问题,是的,有这样的回复。来自 RFC 2616-section 10 (强调):

10.2.5 204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

因此从 flask 你可以做这样的事情。请记住,响应不得包含消息正文,因此您要发回的任何数据都应放入 cookie 中。

@app.route('/')
def index():
    r = flask.Response()
    r.set_cookie("My important cookie", value=some_cool_value)
    return r, 204

关于python - 发送不改变用户当前页面的 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735900/

相关文章:

python - Django - 运行测试时必须使用对象 pk 或 slug 调用通用详细信息 View

python - Bluemix Flask 应用程序不再构建

python - 如何从python中的http响应urllib获取有关大小的信息

html - 如何删除mvc中的http响应头?

python - 游标在 Python 的 DB-API 中是如何工作的?

Python 请求 + Marketo REST API

python - 如何从 python shell 提交并推送到 github?

javascript - 检查设备是否在 Flask 中移动

python - 我如何要求对/admin 路径下的任何内容进行身份验证?

java - Java 中的 HTTP 响应代码