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

Send HTTP response that doesn't change the user's current page

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

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

然后我想这可能是一些让客户端知道信息已成功提交的 HTTP 响应,但会让客户端留在当前页面上。假设 header 值如 "Here is the result of your request, but you should not alter your current display"?

不,这是不可能的。 Flask 建立在 Werkzeug 之上,它实现了 WSGI 规范。 WSGI 循环要求对每个请求发送响应。删除响应需要在比 HTTP 低得多的级别上控制 TCP/IP 连接。这在 WSGI 的领域之外,因此在 Flask 的领域之外。

你可以 return 一个错误代码,或者一个空的正文,但你必须 return 一些东西

return ''  # empty body

回答你修改后的问题,是的,有这样的回复。来自 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.

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

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