Flask 蓝图问题,无法删除 /home 路由,或应用程序崩溃

问题描述

您好,我正在创建一个 Flask 网络应用程序,现在我必须创建更多的 cruds,所以我决定使用蓝图对应用程序进行模块化。

我在 main.py 上有一个登录功能,可以让我进入应用程序界面:

app.route('/',methods=['GET','POST'])
def login():
    # Output message if something goes wrong...
    msg = ''
    # Check if "username" and "password" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']
        # Check if account exists using MysqL
        cursor = MysqL.connection.cursor(MysqLdb.cursors.DictCursor)
        cursor.execute(
            'SELECT * FROM accounts WHERE username = %s AND password = %s',(username,password,))
        # Fetch one record and return result
        account = cursor.fetchone()
        # If account exists in accounts table in out database
        if account:
            # Create session data,we can access this data in other routes
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['username']
            # Redirect to home page
            return redirect(url_for('client.home'))
        else:
            # Account doesnt exist or username/password incorrect
            msg = 'Incorrect username/password!'
    # Show the login form with message (if any)
    return render_template('index.html',msg=msg)

重定向到这个蓝图:

from flask import Blueprint,render_template
from flask import render_template,request,redirect,url_for,session,flash
from flask_MysqLdb import MysqL
import MysqLdb.cursors
import re
from extension import MysqL

client = Blueprint('client',__name__,static_folder="../static",template_folder="../templates")


@client.route('/')
def home():
    if 'loggedin' in session:
        cur = MysqL.connection.cursor()
        cur.execute('SELECT * FROM cliente')
        data = cur.fetchall()
        # User is loggedin show them the home page
        return render_template('home.html',username=session['username'],cliente=data)
    # User is not loggedin redirect to login page
    return redirect(url_for('login'))

它工作得很好,但有条件。在我的 main.py 上,我也有这个:

@app.route('/home')
def home():
    pass

这就是问题所在,我不知道为什么我应该在 main.py 上保留这条路由,因为如果我删除它,我的应用程序就会崩溃并抛出这个错误

werkzeug.routing.BuildError werkzeug.routing.BuildError:无法为端点“home”构建 url。您是指“client.home”吗?

我不知道为什么会发生这种情况。 我为什么要保留这条路线?或者我做错了什么? 你能帮我一把吗? 我试图将重定向更改为使用多个路由,但是如果我删除了该 /home 路由......我的应用程序无论如何都会崩溃。

解决方法

url_for 中查找函数的名称,即 url_for('function_name',parameters)

因此为了更好地避免崩溃,最好将 main.py home 函数的名称更改为其他名称。

,

已解决:我在其他文件上有一个对 Home 的引用:Layout.html。 刚刚删除了 ref 就解决了