Kevin Bradley
Kevin Bradley

Reputation: 111

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'

Upvotes: 10

Views: 15363

Answers (2)

Benjamin Andoh
Benjamin Andoh

Reputation: 335

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

Upvotes: 6

therealak12
therealak12

Reputation: 1316

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

Upvotes: 17

Related Questions