TypeError:哈希必须是unicode或字节,而不是Builtin_function_or_method

时间:2018-07-15 08:35:00

标签: flask jwt flask-restful passlib

我正在尝试对Flask应用实施 JWT 授权。但是,当我尝试登录时,它返回一个带有{TypeError:哈希必须是unicode或字节,而不是Builtin_function_or_method”的"500 Internal server error"。我在这里可能会错过什么?

这是来自models.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

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

您需要更改

Future

Future

但是您没有存储那些使您的所有加密无用的哈希。

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

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