title: Flask User Login - check if user exists
body: <p>I've implemented a login for my flask application, it works when I log users in with the correct credentials, however when I attempt to login with a user that does not exist, I'm hit with this error message:</p>
  
  <p>TypeError: 'NoneType' object is not subscriptable</p>
  
  <p>How can I fix this to ensure that there is a check in place that will return a message, rather then an error ?<a href="https://i.stack.imgur.com/qR7ht.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qR7ht.png" alt="Traceback"></a></p>
  
  <pre><code># user login
  @app.route('/login',methods=['GET','POST'])
  def login():
      if request.method == 'POST':
      # Get Fields Username &amp; Password
      # Client Side Login &amp; Validation handled by wtforms in register class
          username = request.form['username']
          usr_entered = request.form['password']
          #usr_entered = {k: (v).encode("utf-8") for k,v in usr_entered()}
  
  
          cursor = cnx.cursor(dictionary=True,buffered=True)
  # Need to check if the username exists in the db first
  # Get User By Username
          cursor.execute("SELECT * FROM users WHERE username =%s", [username])
          if cursor is not None:
          # Get Stored Hased and Salted password - Need to change fetch one to only return the one username
              data =cursor.fetchone()
              password = data['password']
  # Compare Password with hashed password- Bcrypt
              if bcrypt.checkpw(usr_entered.encode('utf-8'),password.encode('utf-8')):
          #if (usr_entered==password):
                  app.logger.info('Password Matched')
                  session['logged_in'] = True 
                  session['username'] = username
  
                  flash('You are now logged in','success')
                  return redirect(url_for('dashboard'))
              # Close Connection
                  cursor.close()
              else:
                  error = 'Invlaid Username or Password'
                  return render_template('login.html',error=error)
  
      else: 
         error = 'Username not found'
         return render_template('login.html', error=error)
  
      return render_template('login.html')
  </code></pre>