개발하는 체대생

[문제해결][로그인 기능]AttributeError: 'str' object has no attribute 'decode’ 문제 해결 본문

프로젝트

[문제해결][로그인 기능]AttributeError: 'str' object has no attribute 'decode’ 문제 해결

개발하는체대생

문제 원인 : 'str' object has no attribute 'decode’ :  'str' 객체는 'decode’ 할게 없다. 즉, decode할게 없다는 뜻

 

 

@app.route('/api/login', methods=['POST'])
def api_login():
    id_receive = request.form['id_give']
    pw_receive = request.form['pw_give']

    # 회원가입 때와 같은 방법으로 pw를 암호화합니다.
    pw_hash = hashlib.sha256(pw_receive.encode('utf-8')).hexdigest()

    # id, 암호화된pw을 가지고 해당 유저를 찾습니다.
    result = db.user.find_one({'id': id_receive, 'pw': pw_hash})

    # 찾으면 JWT 토큰을 만들어 발급합니다.
    if result is not None:
        # JWT 토큰에는, payload와 시크릿키가 필요합니다.
        # 시크릿키가 있어야 토큰을 디코딩(=풀기) 해서 payload 값을 볼 수 있습니다.
        # 아래에선 id와 exp를 담았습니다. 즉, JWT 토큰을 풀면 유저ID 값을 알 수 있습니다.
        # exp에는 만료시간을 넣어줍니다. 만료시간이 지나면, 시크릿키로 토큰을 풀 때 만료되었다고 에러가 납니다.
        payload = {
            'id': id_receive,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=5)
        }

        token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode('utf-8')

        # token을 줍니다.
        return jsonify({'result': 'success', 'token': token})
    # 찾지 못하면
    else:
        return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode('utf-8')

이 부분에서 문제 발생

token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

.decode('utf-8') 이라는 메서드를 제거해 주면 정상작동!!

 

 

※로컬에서 실행 시에는 .decode('utf-8')를 제거해주지만 배포할 때는 .decode('utf-8') 붙혀서 실행!!!!

Comments