TypeError:哈希必须是unicode或字节,而不是内置的_function_or_method



我正在尝试对Flask应用程序实现JWT授权。然而,当我尝试登录时,它会返回一个"500 Internal server error",并带有"TypeError:哈希必须是unicode或字节,而不是内置的_function_or_method"。我在这里会错过什么。

这是我的模型类。py

from passlib.hash import pbkdf2_sha256
# Create classes to store data.
class User:
""" This class provides a way to store user data. """
users = [
{
'id': 1,
'username': u'mwinel',
'email': u'mwinel@example.com',
'password': u'code618'
},
{
'id': 2,
'username': u'lucy',
'email': u'lucy@example.com',
'password': u'123456'
}
]
def __init__(self, id, username, email, password):
""" Initialize objects. """
self.id = user_id,
self.username = username,
self.email = email,
self.password = password
@staticmethod
# Generate a hashed string to be
# stored by our class model.
def generate_hash(password):
hash = pbkdf2_sha256.encrypt(password, rounds = 20000, salt_size = 16)
return hash
@staticmethod
# Check a given password.
def verify_hash(password, hash):
return pbkdf2_sha256.verify(password, hash)

这是我的登录方法

from flask_restful import Resource, reqparse
from app.models import User
class UserLogin(Resource):
# Call the method to login a user.
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('username', required = True)
parser.add_argument('password', required = True)
data = parser.parse_args()
username = data['username']
password = data['password']
for user in User.users:
if password == User.verify_hash(data['password'], hash):
return {
'message': 'Logged in as {}'.format(data['username']),
}, 200
return {
'message': 'Something went wrong'
}, 500

这是错误

TypeError: hash must be unicode or bytes, not builtin_function_or_method

当到达此行时,您根本没有定义哈希:

if password == User.verify_hash(data['password'], hash):

我相信这通常会引发NameError,但有一个名为hash的内置python函数正试图传递到您的verify_hash方法中(https://docs.python.org/3.5/library/functions.html#hash)。这就是导致您的程序在出现该异常时崩溃的原因。

您需要更改

if password == User.verify_hash(data['password'], hash):

对于

if password == User.verify_hash(data['password'], user['hash']):

但你没有存储那些散列,这使得你所有的加密都毫无用处。

相反,使用哈希函数将密码哈希存储在用户数组中,如下所示:

# Create classes to store data.
class User:
""" This class provides a way to store user data. """
users = [
{
'id': 1,
'username': u'mwinel',
'email': u'mwinel@example.com',
'hash': u'$pbkdf2-sha256$20000$OCeEcM55zzlnbG3tfW9tTQ$k3dRDawLaOMlR4cehJEP/2b0JUTMrtPedzLYxNQWICM'
},
{
'id': 2,
'username': u'lucy',
'email': u'lucy@example.com',
'password': u'$pbkdf2-sha256$20000$8D6H0Npbaw3BWGsNYSxFyA$FxkRkBXuQy8VFRX8dSdygzQ4vNlvFJl6hWZQ6LT2NIc'
}
]

相关内容

  • 没有找到相关文章

最新更新