Skip to main content
 首页 » 编程设计

python之在不呈现重定向页面的情况下进行重定向

2025年05月04日19zhoujg

在用户提交一些数据以创建新对象后,我希望后端像往常一样将他重定向到对象详细信息:

我正在做类似的事情:

if obj.is_valid(): 
    obj.save() 
    flash('%s created' % obj, ) 
    return redirect(url_for('provider', provider_id=obj.id)) 

但是通过 curl 做 te 请求(我正在构建一个 API,用 curl 测试它)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 
<title>Redirecting...</title> 
<h1>Redirecting...</h1> 
<p>You should be redirected automatically to target URL: <a href="/provider/11">/provider/11</a>.  If not click the link. 
user@box 

这很不幸,因为我只想要 /provider/:id 的响应而不是中间步骤。

解决这个问题的正确方法是什么?

请您参考如下方法:

实际上,Flask 在这里按照RFC 2616 section 10.3.2 的定义做了正确的事情

The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

[强调我的]

引用 RFC 2119 ,这一段可以解释为:

HTTP servers must include a short hypertext note with 30X redirects unless they have a very good reason to avoid doing so

任何使用浏览器或任何通用 HTTP 库的人都不会看到该页面 - 客户端将遵循 RFC 2616 相关部分中指定的 Location header 中提供的重定向。

除了悬而未决的讲授,如果您正在构建一个 JSON API 并且除了状态代码和必要的 header 之外您不想提供任何服务,您可以通过使用 Flask.errorhandler 为适当的方法注册您自己的错误处理程序来实现。装饰器或 Flask.register_error_handler :

@app.errorhandler(302) 
def minimal_redirect(): 
    return u"", 302