python flask render_template html无法正确呈现

时间:2017-02-23 03:34:57

标签: python flask

我正在构建一个实现用户登录的python烧瓶应用,在用户成功登录后,它将重定向到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页面。 这让我困惑了好几天,感谢提前。

1 个答案:

答案 0 :(得分:1)

因为我不知道如何向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”,并且只能在他未登录时查看该页面。

我希望你觉得这很有用。