简体   繁体   中英

AttributeError: 'str' object has no attribute 'decode' python error

this is my code

@app.route("/api/v1.0/login", methods=["GET"] )
def login():
    auth = request.authorization
    if auth:
        user = users.find_one( { "username" : auth.username } )
        if user is not None:
            if bcrypt.checkpw(bytes(auth.password, 'UTF-8'), user["password"]):
                token = jwt.encode({
                    'user' : auth.username,
                    'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
                return make_response( jsonify({'token' : token.decode('UTF-8')}), 200)
            else: 
                return make_response(jsonify({"message" : "Bad password"} ) )
        else: 
            return make_response(jsonify({"message" : "Bad username" } ) )

    return make_response(jsonify({ "message" : "Authentication required"}))

and this is error

AttributeError: 'str' object has no attribute 'decode'

If you are using PyJwt module, then there is no need to decode the token. jwt.encode({some_dict}) returns the token you need.

this worked for me, i only returned the token (i initially had 'return token.decode('utf-8')' but later took the decode function off)

   def _generate_jwt_token(self):
        dt = datetime.now() + timedelta(days=60)
        token = jwt.encode({
            'id': self.pk,
            'exp': dt.utcfromtimestamp(dt.timestamp())},
            settings.SECRET_KEY, algorithm='HS256')
        return token

In python 3, delete simply.decode('UTF-8')

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