您好,我正在创建一个 Flask Web 应用程序,现在我必须创建更多的 crud,所以我决定使用蓝图对应用程序进行模块化。
我在 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 路由.. 我的应用程序无论如何都会崩溃。