[파이썬 REST API #6]

강지훈·2022년 9월 22일
0

[파이썬 REST API#6]
파이썬 REST API로 이름 바꾸고 첫 포스팅

사용법 main.py를 cmd에서 실행해서 서버를 열어준다
또 다른 cmd를 켜서 같은 경로에서 test.py를 실행시킨다.

[main.py]
from urllib import request
from flask import Flask
from flask_restful import Api, Resource,reqparse,abort

app = Flask(name)
api = Api(app)

video_put_args = reqparse.RequestParser()
video_put_args.add_argument("name",type=str, help="Name of video", required=True)
video_put_args.add_argument("views",type=int, help="views of the video" ,required=True)
video_put_args.add_argument("likes",type=int, help="Likes on the video" ,required=True)

videos = {}

def abort_if_video_id_doesnt_exist(video_id):
if video_id not in videos:
abort(404,message="Could not find video...")

class Video(Resource):
def get(self, video_id):
abort_if_video_id_doesnt_exist(video_id)
return videos[video_id]

def put(self, video_id):
    args= video_put_args.parse_args()
    videos[video_id] = args
    return videos[video_id], 201

api.add_resource(Video,"/video/<int:video_id>")

if name == "main":
app.run(debug=True)

[test.py]
import requests

BASE = "http://127.0.0.1:5000/"

#response = requests.put(BASE + "video/1",{"likes":10,"name":"time","views":10000})
#print(response.json())

#input()
response = requests.get(BASE + "video/6")
print(response.json())

// video/6 요청을 보냈는데 video/6 이 없기떄문에 could not fine video 메시지를 출력한다.

profile
never stop

0개의 댓글