Flask中'/'路由未单独绑定处理函数的路由规则解析
Flask同函数绑定多路由的匹配逻辑说明
这是Flask路由装饰器的标准用法,不存在隐式特殊匹配规则:
- Flask支持给同一个视图函数叠加多个
@app.route()装饰器,所有装饰器声明的路由规则都会绑定到下方同一个处理函数,不需要为每个路由单独编写独立处理函数。 - 示例代码里,根路径
/的路由规则由第一行@app.route('/')声明,和下方/login的路由规则共同绑定到login()视图函数:@app.route('/') @app.route('/login', methods =['GET', 'POST']) def login(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form: username = request.form['username'] password = request.form['password'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s AND password = % s', (username, password, )) account = cursor.fetchone() if account: session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] msg = 'Logged in successfully !' return render_template('index.html', msg = msg) else: msg = 'Incorrect username / password !' return render_template('login.html', msg = msg) - 具体路由匹配逻辑:
- 未显式指定
methods参数的路由装饰器,默认仅接受GET、HEAD请求方法,因此访问根路径/的GET请求会直接命中路由规则,进入login()函数执行 - 函数执行时判断当前请求为GET方法、未提交合法登录表单参数,会直接走到最后一行逻辑返回
login.html页面,也就是未登录访问根路径加载登录页的效果 - 只有
/login路径显式声明支持POST方法,直接向根路径/提交POST登录请求会返回405方法不允许错误,使用时需要注意区分。
- 未显式指定
内容的提问来源于stack exchange,提问作者Saniaaa
相关产品推荐
相关产品推荐

