3. 팔로우 & 언팔로우

전송할 JSON

{
	"id" : 1,
    "follow" : 2
 }

 

팔로우

@app.route("/follow", method=['POST'])
def follow():
    payload = request.json
    user_id = int(payload["id"])
    user_id_to_follow = int(payload["follow"])

    if user_id not in app.user or user_id_to_follow not in app.users:
        return "사용자가 존재하지 않습니다", 400

    user = app.users[user_id]
    user.setdefault('follow', set()).add(user_id_to_follow)

    return jsonify(user)
@app.route("/follow", method=['POST'])
def follow():
    payload = request.json
    user_id = int(payload["id"])
    user_id_to_follow = int(payload["follow"])

    if user_id not in app.user or user_id_to_follow not in app.users:
        return "사용자가 존재하지 않습니다", 400

    user = app.users[user_id]
    user.setdefault('follow', set()).add(user_id_to_follow)
    # 사용자가 다른 사용자를 follow한 적이 있다면 사용자의 follow키와 연결되어 있는 set에 팔로우 하고 하는 사용자 아이디를 추가
    # 만약 처음이라면 emtpy set과 연결하여 추가
    # 키가 존재하지 않으면 default 값으로 저장
    # 키가 존재하면 해당값을 읽음

    return jsonify(user)

 

실행

http -v POST localhost:5000/sign-up name="현욱" && http -v POST localhost:5000/sign-up name="라이언" && http -v POST localhost:5000/follow id=1 follow=2

 

TypeError: Object of type set is not JSON serializable 에러발생

-> set을 파이썬의 json 모듈이 JSON으로 변경하지 못해서 생기기 때문

-> JSONEncoder 임포트

import os
from flask import Flask, jsonify, request 
from flask.json import JSONEncoder

class CustomJSONEncoder(JSONEncoder):  # 1
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return JSONEncoder.default(self, obj)

app = Flask(__name__)
app.users = {}
app.id_count = 1
app.tweets = []
app.json_encoder = CustomJSONEncoder



@app.route("/ping", methods=["GET"])
def ping():
    return "pong"


@app.route("/sign-up", methods=["POST"])  
def sign_up():
    new_user = request.json 
    new_user["id"] = app.id_count
    app.users[app.id_count] = new_user
    app.id_count += 1
    return jsonify(new_user) 


@app.route("/tweet", methods=["POST"])  
def tweet():
    payload = request.json
    user_id = int(payload["id"])
    tweet = payload["tweet"]

    if user_id not in app.users:
        return "사용자가 존재하지 않습니다", 400

    if len(tweet) > 300:
        return "300자를 초과했습니다", 400

    app.tweets.append({"user_id": user_id, "tweet": tweet})

    return "", 200

@app.route("/follow", methods=["POST"])
def follow():
    payload = request.json
    user_id = int(payload["id"])
    user_id_to_follow = int(payload["follow"])

    if user_id not in app.users or user_id_to_follow not in app.users:
        return "사용자가 존재하지 않습니다", 400

    user = app.users[user_id]
    user.setdefault("follow", set()).add(user_id_to_follow)

    return jsonify(user)

 

결과

$ http -v POST localhost:5000/sign-up name="현욱" && http -v POST localhost:5000/sign-up name="라이
언"&&& http -v POST localhost:5000/follow id=1 follow=2
POST /sign-up HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 24
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "name": "현욱"
}


HTTP/1.0 200 OK
Content-Length: 41
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:29:13 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "id": 1,
    "name": "현욱"
}


POST /sign-up HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 30
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "name": "라이언"
}


HTTP/1.0 200 OK
Content-Length: 47
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:29:17 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "id": 2,
    "name": "라이언"
}


POST /follow HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 26
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "follow": "2",
    "id": "1"
}


HTTP/1.0 200 OK
Content-Length: 67
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:29:20 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "follow": [
        2
    ],
    "id": 1,
    "name": "현욱"
}

 

언팔로우

@app.route("/unfollow", methods=["POST"])  # 4
def unfollow():
    payload = request.json
    user_id = int(payload["id"])
    user_id_to_unfollow = int(payload["unfollow"])

    if user_id not in app.users or user_id_to_unfollow not in app.users:
        return "사용자가 존재하지 않습니다", 400

    user = app.users[user_id]

    if not user.get("follow") or len(user.get("follow")) == 0:
        return "팔로우하고 있는 사용자가 없습니다", 400

    user.setdefault("follow", set()).discard(user_id_to_unfollow)
    
    return jsonify(user)

 

결과

$ http -v POST localhost:5000/sign-up name="현욱" && http -v POST localhost:5000/sign-up name="라이
언" && http -v POST localhost:5000/follow id=1 follow=2 && http -v POST localhost:5000/unfollow id=1 unfollow=2
POST /sign-up HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 24
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "name": "현욱"
}


HTTP/1.0 200 OK
Content-Length: 41
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:33:47 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "id": 1,
    "name": "현욱"
}


POST /sign-up HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 30
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "name": "라이언"
}


HTTP/1.0 200 OK
Content-Length: 47
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:33:50 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "id": 2,
    "name": "라이언"
}


POST /follow HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 26
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "follow": "2",
    "id": "1"
}


HTTP/1.0 200 OK
Content-Length: 67
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:33:54 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "follow": [
        2
    ],
    "id": 1,
    "name": "현욱"
}


POST /unfollow HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 28
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/2.4.0

{
    "id": "1",
    "unfollow": "2"
}


HTTP/1.0 200 OK
Content-Length: 58
Content-Type: application/json
Date: Mon, 15 Feb 2021 14:33:58 GMT
Server: Werkzeug/1.0.1 Python/3.8.5

{
    "follow": [],
    "id": 1,
    "name": "현욱"
}
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기