我试图用烧瓶编写邮路线,但是每次我测试路由时,它都用相同的URL重定向,但作为get请求。我不想要它,因为我需要帖子主体。
我不明白烧瓶为什么这样做。
进一步令人困惑的是,在同一烧瓶应用程序中,还有另一条不重新定向的路线。
我还尝试仅将"帖子"设置为允许的方法,但是该路由仍被重定向,并且响应是不允许的405方法,这是合乎逻辑的,因为我设置了该方法是不允许的方法。但是,为什么它根本重定向并自身呢?
访问日志:
<redacted ip> - - [14/Feb/2019:11:32:39 +0000] "POST /service HTTP/1.1" 301 194 "-" "python-requests/2.21.0"
<redacted ip> - - [14/Feb/2019:11:32:43 +0000] "GET /service HTTP/1.1" 200 8 "-" "python-requests/2.21.0"
应用程序代码,请注意,两条路线分别没有,并进行重定向:
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
@app.route('/path/does/not/redirect')
def notredirected():
url_for('static', filename='style.css')
return render_template('template.html')
@app.route('/service', strict_slashes=True, methods=["GET", "POST"])
def service():
return "Arrived!"
return app
app = create_app()
我的预期结果是,POST /service
将返回200并到达!作为其输出。
编辑:如果我将路由签名更改为:@app.route('/service', strict_slashes=True, methods=["POST"])
,它仍将其重定向到GET请求,然后返回405,因为没有/服务的途径。
<redacted> - - [14/Feb/2019:13:05:27 +0000] "POST /service HTTP/1.1" 301 194 "-" "python-requests/2.21.0"
<redacted> - - [14/Feb/2019:13:05:27 +0000] "GET /service HTTP/1.1" 405 178 "-" "python-requests/2.21.0"
您的service
路由已配置为处理get and post requests ,但是您的service
Route 没有区分传入的get和发布请求。默认情况下,如果您没有在路由上指定受支持的方法,则烧瓶默认为支持GET请求。但是,没有检查传入请求,您的service
Route 不知道如何处理传入请求,因为均受支持和发布,因此它尝试重定向以处理请求 。一个简单的条件如下:if flask.request.method == 'POST':
可用于区分两种类型的请求。话虽如此,也许您可以尝试以下内容:
@app.route('/service', methods=['GET', 'POST'])
def service():
if request.method == "GET":
msg = "GET Request from service route"
return jsonify({"msg":msg})
else: # Handle POST Request
# get JSON payload from POST request
req_data = request.get_json()
# Handle data as appropriate
msg = "POST Request from service route handled"
return jsonify({"msg": msg})
问题是服务器将所有非HTTPS请求重定向到我不知道的HTTPS变体。由于这对我们来说不是问题的行为,因此在客户端指定了使用HTTPS的解决方案。