gpt4 book ai didi

python Flask render_template html 未正确渲染

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:37 25 4
gpt4 key购买 nike

我正在构建一个Python Flask应用程序实现用户登录,用户成功登录后,它将重定向到userHome.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Flask Bucket List App</title>
    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
 
    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/css/signup.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="/logout">Logout</a>
                    </li>
                </ul>
            </nav>
            <h3 class="text-muted">Python Flask App</h3>
        </div>
 
        <div class="jumbotron">
            <h1>Welcome Home !!</h1>  
        </div> 
        <footer class="footer">
            <p>&copy; Company 2015</p>
        </footer>  
    </div>
</body>
</html>

以及执行return render_template('userHome.html')的Python代码在validateLogin中:

@app.route('/validateLogin',methods=['POST'])
def validateLogin():
cursor = None
try:
_username = request.form['inputName']
_password = request.form['inputPassword']

# connect to mysql

conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_validateLogin',(_username,_password))
data = cursor.fetchall()

if len(data) > 0:
return render_template('userHome.html')
else:
return render_template('error.html', error = "Wrong Username or
Password")

except Exception as e:
return render_template('error.html',error = str(e))
finally:
if cursor:
cursor.close()
conn.close()

signin.js:

  $(function(){
$('#btnSignIn').click( function(){

$.ajax({
url: '/validateLogin',
data: $('form').serialize(),
type: "POST",
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});

最后是signin.html:

!DOCTYPE html>
<html lang="en">
<head>
<title>Sign In</title>


<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<link href="../static/signup.css" rel="stylesheet">
<script src="/static/js/jquery-3.1.1.js"></script>
<!--<script src="/static/js/jquery-3.1.1.min.map"></script>-->
<script src="/static/js/signin.js"></script>

</head>

<body>

<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" ><a href="main">Home</a></li>
<li role="presentation" class="active"><a href="#">Sign In</a></li>
<li role="presentation"><a href="showSignUp">Sign Up</a></li>

</ul>
</nav>
<h2 class="text-muted">Release Control System</h2>
</div>

<div class="jumbotron">
<h1>Log In</h1>
<form class="form-signin">
<label for="inputName" class="sr-only">Name</label>
<input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
<!--<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>-->
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>

<button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="button">Sign in</button>
</form>
</div>



<footer class="footer">
<p>Copyright 2017 Foxconn CABG &copy; All Rights Reserved.</p>
</footer>

</div>
</body>
</html>

但是当我成功登录时,它不会定向到 userHome.html 页面,而是显示所有 html 实体。这意味着模板正在工作,但浏览器处理错误。

我尝试过很多技巧,例如:

    headers = {'Content-Type': 'text/html'}
return make_response(render_template('userHome.html'),200,headers)

但它仍然返回 html 实体,而不是 html 页面。这让我困惑了好几天,先谢谢了。

最佳答案

因为我不知道如何向ajax发送重定向请求并执行它。我就简单分享一下我做事的方法。

# Python Code
@app.route('/login')
def login():
# check if user is not logged in then render the login form
if user_not_logged_in():
return render_template('login_form.html')
# if user logged in, then redirect to userHome
else:
return redirect(url_for('userHome'))

from flask import jsonify
@app.route('/validateLogin', methods=['POST'])
def validateLogin():
# do some stuff and check for validation
if stuff_goes_well:
return jsonify({'data': 'success'})
else:
return jsonify({'data': 'failure'})

@app.route('/userHome')
def userHome():
# check if user is logged in
if logged_in_user_session_exists():
return render_template('userHome.html')
else:
# user is not logged in so redirect him to the login page
return redirect(url_for('login'))

# jQuery code
$.ajax({
url: "/validateLogin",
type: "POST",
dataType: "json",
data: data_here,
success: function(response){
if(response.data == 'success'){
# success was sent so the user logged in successfully, redirect to user home
window.location.replace('/userHome');
}else{
# there was an error in the logging in
alert('there was an error!');
}
}
});

用几句话总结一下:只需使用 ajax 将数据发送到 Python 即可。然后让Python处理数据的验证和分析。然后如果一切顺利,告诉 jQuery“嘿,这里一切都很酷”(由我们发送的“成功”字符串表示)。如果出现问题,我们会告诉 jQuery 我们遇到了问题,因此我们会发送“失败”字符串。然后在 jQuery 中我们对发送的字符串进行操作。如果成功,那么我们将用户重定向到所需的 URL(在本例中为/userHome)。如果发送失败,那么我们就说出现了错误。

请注意,这些 python 检查很重要,因此用户不必在 URL 中键入“/userHome”,并且可以在未登录时查看页面。

我希望您觉得这很有用。

关于python Flask render_template html 未正确渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42406516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com