没有训练斜杠的URL中的FormDataRoutingRedirect异常

时间:2013-11-29 21:07:09

标签: python url flask python-2.6

我正在做一个ajax POST请求,我得到了这个例外:

[Fri Nov 29 20:48:55 2013] [error] [client 192.168.25.100]     self.raise_routing_exception(req)
[Fri Nov 29 20:48:55 2013] [error] [client 192.168.25.100]   File "/usr/lib/python2.6/site-packages/flask/app.py", line 1439, in raise_routing_exception
[Fri Nov 29 20:48:55 2013] [error] [client 192.168.25.100]     raise FormDataRoutingRedirect(request)
[Fri Nov 29 20:48:55 2013] [error] [client 192.168.25.100] FormDataRoutingRedirect: A request was sent to this URL (http://example.com/myurl) but a redirect was issued automatically by the routing system to "http://example.com/myurl/".  The URL was defined with a trailing slash so Flask will automatically redirect to the URL with the trailing slash if it was accessed without one.  Make sure to directly send your POST-request to this URL since we can't make browsers or HTTP clients redirect with form data reliably or without user interaction.

路线定义是:

@app.route('/myurl')
def my_func():

我可以在Firebug中看到请求是在没有尾部斜杠的情况下发送的:

http://example.com/myurl
Content-Type    application/x-www-form-urlencoded; charset=UTF-8

我在另一个模块中有这个:

@app.route('/')
@app.route('/<a>/')
@app.route('/<a>/<b>')
def index(a='', b=''):

这最后一个会妨碍吗?或者是什么? Flask版本为0.10.1

1 个答案:

答案 0 :(得分:7)

我的猜测是,您的/myurl路由未定义为接受POST个请求,而您的/<a>/路由是,因此Werkzeug选择了/<a>/

解释以斜杠结尾的路由的行为here。默认情况下,调用使用尾部斜杠定义的路径而不使用该斜杠会触发重定向到URL的尾部斜杠版本。这当然不适用于POST次请求,因此您获得FormDataRoutingRedirect例外。

我怀疑如果您将POST请求发送到/myurl/,那么您的/<a>/路由会被调用得很好,但显然这不是您想要的。

我认为您遗失的是接受POST /myurl的请求,您可以执行以下操作:

@app.route('/myurl', methods = ['GET', 'POST'])
def my_func():