在烧瓶中重定向时发出POST请求 [英] Make a POST request while redirecting in flask

查看:151
本文介绍了在烧瓶中重定向时发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用烧瓶工作。
我处于这种情况,我需要重定向一个post请求到另一个保存请求方法的url,即POST方法。当我将一个GET请求重定向到另一个接受GET请求方法的URL时,就没有问题了。
这里是我正在尝试上面的示例代码。

  @ app.route('/ start' ,方法= ['POST'])
def start():
flask.redirect(flask.url_for('operation'))

@ app.route('操作',methods = ['POST'])
def操作():
返回我的回应

我想发一个POST请求到/ starturl,这个请求在内部也会向/ operationurl发送一个POST请求。如果我像这样修改代码,

  @ app.route('/ operation',methods = ['GET'])
def操作():
returnMy Response

代码对于GET请求正常工作。但是我也希望能够发出POST请求。

解决方案

redirect 中提供的函数c> Flask 默认向客户端发送一个302状态码,正如 $ b


许多网页浏览器以违反这个标准的方式实现这个代码,改变
GET新请求的请求类型,而不管原始
请求(例如POST)中使用的类型如何。 [1]为此,HTTP / 1.1(RFC 2616)添加了新的状态码
303和307来消除这两种行为之间的歧义,其中303要求将
请求类型更改为GET,307保留原始发送的请求类型。

因此,发送307状态代码而不是302应该告诉浏览器保存使用的HTTP方法,从而有你期望的行为。您对 redirect 的调用将如下所示:

  flask.redirect (flask.url_for('operation'),code = 307)


I am working with flask. I am in a situation where I need to redirect a post request to another url preserving the request method i.e. "POST" method. When I redirected a "GET" request to another url which accepts "GET" request method is fine. Here is sample code with which I am trying the above..

@app.route('/start',methods=['POST'])
def start():
    flask.redirect(flask.url_for('operation'))

@app.route('/operation',methods=['POST'])
def operation():
    return "My Response"

I want to make a "POST" request to "/start" url which internally also makes a "POST" request to "/operation" url.If I modify code as like this,

@app.route('/operation',methods=['GET'])
def operation():
    return "My Response"

code works fine for "GET" request. But I want to be able to make POST request too.

The redirect function provided in Flask sends a 302 status code to the client by default, and as mentionned on Wikipedia:

Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g. POST). [1] For this reason, HTTP/1.1 (RFC 2616) added the new status codes 303 and 307 to disambiguate between the two behaviours, with 303 mandating the change of request type to GET, and 307 preserving the request type as originally sent.

So, sending a 307 status code instead of 302 should tell the browser to preserve the used HTTP method and thus have the behaviour you're expecting. Your call to redirect would then look like this:

flask.redirect(flask.url_for('operation'), code=307)

这篇关于在烧瓶中重定向时发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆