简体   繁体   中英

Return SQL queries via Python to JavaScript?

Let's say I have a form:

<form action="/login" method="post" class="card-title">
   <input class="form-control" name="username" placeholder="Username" type="text"/>
   <input class="form-control" name="password" placeholder="Password" type="password"/>
   <button class="btn" type="submit">Log  In</button>
</form>

This form will submit to the URL '/login' in my Flask app.

If the password is incorrect, I would like to pass it to JavaScript somehow so it can display an error on the login page, currently it just redirects to a 'wrong password' page. The login information is stored in a SQLite database, so that's why I'm passing it to Python.

Any Ideas?

You can create a div below the box that receives the input for the credential/credentials that where in valid:

In the HTML:

<style>
    .invalid_input{ 
     width:100px;
     height:20px;
     border-radius:4px;
     background-color:red;
     color:white;
   }
 </style>
<html>
<form action="/login" method="post" class="card-title">
  <input class="form-control" name="username" placeholder="Username" type="text"/>
  <div class='invalid_input'>{{message_username}}</div>
    <div class='spacer' style='height:10px;'></div>      
   <input class="form-control" name="password" placeholder="Password" type="password"/> 
  <div class='invalid_input'>{{message_password}}</div>
    <div class='spacer' style='height:10px;'></div>
 <button class="btn" type="submit">Log  In</button>
</form>
</html>

Then, in the app (utilizing placeholder lookup functions for username and password):

@app.route('/login', methods = ['GET', 'POST'])
def login():
  if flask.request.method == 'POST':
    username = flask.request.form['username']
    password = flask.request.form['password']
    u_flag, p_flag = is_valid_username(username), is_valid_password(password)
    if not u_flag or not p_flag:
      return flask.render_template('login.html', message_username = '' if u_flag else 'Invalid Username', message_password = '' if p_flag else 'Invalid Password'
  return flask.render_template('login.html', message_username = '', message_password = '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM