首页 > 解决方案 > Flask 运行 request.method 默认为 'POST' 而不是 'GET'

问题描述

我正在开发这个 Flask 应用程序,我在其中按下“登录”按钮,然后被重定向到“仪表板”。

这是我打开登录页面的默认路由的简化代码:

@app.route('/',  methods=['POST', 'GET'])
def home():
    if not session.get('logged_in'): 
        if request.method == 'GET':
            return render_template('login.html')
        elif request.method == 'POST':
            if # Username and Password are correct from the login form
                session['logged_in'] = True
                return dashboard()
            else:
                return render_template('login.html', message = "Wrong username or password")
    else:
        return render_template('dashboard.html')

login.html 有一个表单,form action="/" method="POST"用于触发elif request.method == 'POST'上面默认路由('/')中的条件

这是 route('/dashboard') 的简化代码

@app.route('/dashboard', methods=['POST', 'GET'])
def dashboard():
    if session.get('logged_in'):
        if request.method == 'GET':
            return "it was GET"
        elif request.method == 'POST':
            return "it was POST"
    else:
        return render_template('login.html')

问题来了。仪表板路由在登录后运行 POST 方法,尽管(根据我的概念)它应该运行 GET 方法(因为 GET 是默认的)。

它给出的输出是“它是 POST”。请帮忙。谢谢 :)

标签: pythonhttppostflaskget

解决方案


你不能只打电话return dashboard()。您必须启动重定向 - 告诉浏览器加载/dashboard

return flask.redirect(flask.url_for('dashboard'))

推荐阅读