问题
I am creating a login application using Flask-mysql.
from flask import Flask, jsonify, request, json
from flask_mysqldb import MySQL
from datetime import datetime
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager
from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt)
import yaml
app = Flask(__name__)
alogin = yaml.load(open('alogin.yaml'))
app.config['MYSQL_HOST']= alogin['mysql_host']
app.config['MYSQL_USER']= alogin['mysql_user']
app.config['MYSQL_PASSWORD']= alogin['mysql_password']
app.config['MYSQL_DB']= alogin['mysql_db']
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
app.config['JWT_SECRET_KEY'] = 'secret'
mysql = MySQL(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
CORS(app)
@app.route('/alogin', methods=['POST'])
def login():
cur = mysql.connection.cursor()
email = request.get_json()['email']
password = request.get_json()['password']
result = ""
cur.execute("SELECT * FROM admin where email = '" + str(email) + "'")
rv = cur.fetchone()
if bcrypt.check_password_hash(rv['password'], password):
access_token = create_access_token(identity = {'id':rv['id'],'email': rv['email']})
result = jsonify({"token":access_token})
else:
result = jsonify({"error":"Invalid username and password"})
return result
if __name__ == '__main__':
app.run(debug=True)
I am getting the the error as follows:
if bcrypt.check_password_hash(rv['password'], password):
TypeError: 'NoneType' object is not subscriptable
I have tried using 'force=True' in
email = request.get_json(force = True)['email']
password = request.get_json(force = True)['password']
Yet it is throwing the same error. This is my first application with flask. Help will be appreciated.
PS : admin is the name of the table in the database and I have already created it in the mysql database.
回答1:
fetchone()
will return None
if the query doesn't result in data. Add an
if rv is None:
check to handle the case of someone providing an email address that isn't in the database.
Also, take a moment and look up "SQL Injection Attack".
来源:https://stackoverflow.com/questions/63216396/typeerror-nonetype-object-is-not-subscriptable-in-flask-mysql-application