pwoogi
자신의 왜곡된 경험을 진실이라고 생각하지 말자

웹개발 미니 프로젝트/2일차(07-12) 에러일지 및 기능구현

2일차(07-12) 에러일지 및 기능구현 성공

pwoogi 2022. 7. 13. 01:15

1. 에러일지

  • 로그인 기능 구현 JWT 토큰중에 발생하는 에러
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode('utf-8')

AttributeError: ‘str’ object has no attribute ‘decode’기존 버전에서는 jwt.encode()함수의 리턴값이 '바이트 문자열'이라는 자료형이었기 때문에 뒤에 .decode('utf-8')를 붙여 일반 문자열로 바꾸어주었었는데요, 2.0.0 버전부터는 이 함수의 리턴값이 일반 문자열이기 때문에 여기에 또 .decode('utf-8')를 붙여주게 되면 문자열에는 이런 메소드가 없으므로 에러가 나게 됩니다. (101100100110 같은 바이트 자료를 문자열로 바꾸는 것이 decode이므로 당연히 문자열에는 이런 기능이 필요없다.


  • mongoDB 연결도중 발생하는 에러

pymongo.errors.serverselectiontimeouterror 에러의 경우 DB와 연결해주는 localhost 문제로 예측되어서 기존에 직었던 아래의 코드와는 다르게

client = MongoClient('localhost, 27017, user:xxxx, password:xxxx')

mongoDB 웹에서 직접 링크를 복사해서 붙여줬더니 문제가 발생하지 않았다.


  • mongoDB 설치를 안해서 나는 에러

ServerSelectionTimeoutError: localhost:27017:[WinError 10061] 이 에러는 이미 MongoDB를 웹상에서 동작하게 만들었음에도 불구하고 에러가 나서 찾아봤더니  Window용 mongoDB community server를 다운받으라는 조언들이 많았다. Studio 3T에서도 문제 없이 작동하는 것을 확인했다.


 

2. 기능구현

1. 회원가입, 로그인, 취소 기능 구현

 

2. 로그인 성공 시 다음페이지 이동 및 포스팅 가능

 

 

3. 프로필 수정 및 로그아웃 가능

 

3. 해결해야하는 문제

유저A가 로그인 한 후 유저B의 프로필을 확인하면 profile_info, name, pic 만 확인이 가능하게 하고 포스팅한 글이 나오지 않게 해야하는데 지금 그게 구현이 안되고 있다. 다른 팀원에게 같은 코드를 전달하고 구현을 부탁드렸는데 문제가 없는 것으로 보아 mongoDB과 관련된 문제인 것인가 싶었지만 아직 원인을 잘 모르겠다..

@app.route("/get_posts", methods=['GET'])
def get_posts():
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        username_receive = request.args.get("username_give")
        if username_receive == "":
            posts = list(db.posts.find({}).sort("date", -1).limit(20))
        else:
            posts = list(db.posts.find({"username": username_receive}).sort("date", -1).limit(20))
        for post in posts:
            post["_id"] = str(post["_id"])
            post["count_heart"] = db.likes.count_documents({"post_id": post["_id"], "type": "heart"})
            post["heart_by_me"] = bool(db.likes.find_one({"post_id": post["_id"], "type": "heart", "username": payload['id']}))
        return jsonify({"result": "success", "msg": "포스팅을 가져왔습니다.", "posts": posts})
    except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):
        return redirect(url_for("home"))
<script>

        $(document).ready(function () {
            get_posts('{{ user_info.username }}');
        })

        function sign_out() {
            $.removeCookie('mytoken', {path: '/'});
            alert('로그아웃!')
            window.location.href = "/login"
        }

        function update_profile() {
            let name = $('#input-name').val()
            let file = $('#input-pic')[0].files[0]
            let about = $("#textarea-about").val()
            let form_data = new FormData()
            form_data.append("file_give", file)
            form_data.append("name_give", name)
            form_data.append("about_give", about)
            console.log(name, file, about, form_data)

            $.ajax({
                type: "POST",
                url: "/update_profile",
                data: form_data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    if (response["result"] == "success") {
                        alert(response["msg"])
                        window.location.reload()

                    }
                }
            });
        }
    </script>
sparta123의 아이디로 sparta1234의 프로필 포스팅이 보이고 있다..

 

오늘도 분노 + 1 스택