본문 바로가기

BackEnd/Python-Flask

[백엔드] Flask: recipe 프로젝트: API 조회/수정/삭제: GET/PUT/DELETE

반응형

레시피 하나만 조회하는 API

 

 API 설계서 확인

- 하나의 레시피/정보를 가져올것이다. ‘경로/숫자’의 형식으로 경로를 지정할 것이다.

- 우선 [‘GET’]의 API 코드를 작성해보자.

- 항상 vscode에서 코드를 작성하기 전에, 해당 쿼리문이 잘 실행되는지를 mysql에서 확인이 끝나야한다.

 

app.py의 코드는 하기와 같다.

api.add_resource(RecipeResource,'/recipes/<int:recipe_id>')
 # 이 뒤에있는 숫자를 받아, 어디로 처리하라.

# 하나의 경로당, 하나의 class로 처리한다.

 

새로운 파일 recipe_info.py를 생성하여 하기 코드를 작성한다.

from flask import request
from flask_restful import Resource
from mysql.connector.errors import Error
from mysql_connection import get_connection
import mysql.connector

class RecipeResource(Resource) : 
   
    # 클라이언트로부터 /recipes/3 이런식으로 경로를 처리하므로
    # 숫자는 바뀌므로, 변수로 처리해준다.
    def get(self, recipe_id) :

        # DB에서, recipe_id 에 들어있는 값에 해당되는
        # 데이터를 select 해온다.

        try :
            connection = get_connection()

            query = '''select *
                    from recipe
                    where id = %s ;'''
            record = (recipe_id, )
           
            # select 문은, dictionary = True 를 해준다.
            cursor = connection.cursor(dictionary = True)

            cursor.execute(query, record)

            # select 문은, 아래 함수를 이용해서, 데이터를 가져온다.
            result_list = cursor.fetchall()

            print(result_list)

            # 중요! 디비에서 가져온 timestamp 는
            # 파이썬의 datetime 으로 자동 변경된다.
            # 문제는! 이데이터를 json 으로 바로 보낼수 없으므로,
            # 문자열로 바꿔서 다시 저장해서 보낸다.
            i = 0
            for record in result_list :
                result_list[i]['created_at'] = record['created_at'].isoformat()
                result_list[i]['updated_at'] = record['updated_at'].isoformat()
                i = i + 1                

            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()

            return {"error" : str(e)}, 503


        return {'result' : 'success' ,
                'info' : result_list[0]}​

 

레시피 수정/업데이트하는 API

[‘PUT’] 메소드를 이용한다.

 

postman에서 클라에서 보낼 정보를 미리 작성하고 vscode에서 코드를 작성하는 것이 좋다.

전달될 데이터는 name, description, cook_time, directions이다. 

  # 데이터를 업데이트하는 API는  put 함수를 사용한다.
    def put(self, recipe_id) :

        # body에서 전달된 데이터를 처리
        data = request.get_json()

        # 디비 업데이트 실행코드
        try :
            # 데이터 업데이트
            # 1. DB에 연결
            connection = get_connection()

            query = '''select user_id
                        from recipe
                        where id = %s;'''
            record = (recipe_id,)

            # 커서 가져와서 execute
            cursor = connection.cursor(dictionary = True)
            cursor.execute(query, record)

            # 실행을 시키면 result_list가 온다.
            result_list = cursor.fetchall()

            if len(result_lsit) == 0:
                cursor.close()
                connection.close()
                return{'error':'레시피 아이디가 잘못되었습니다.'},400

            # 2. 쿼리문 만들기
            query = '''update recipe
                    set name = %s , description = %s ,
                    cook_time = %s ,
                    directions = %s'''
           
            record = (data['name'], data['description'],
                        data['cook_time'], data['directions'] )

            # 3. 커서를 가져온다.
            cursor = connection.cursor()

            # 4. 쿼리문을 커서를 이용해서 실행한다.
            cursor.execute(query, record)

            # 5. 커넥션을 커밋해줘야 한다 
            connection.commit()

            # 6. 자원 해제
            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()
            return {'error' : str(e)}, 503

        return {'result' :'success'}, 200

 

레시피 삭제하는 API

[‘DELETE’] 메소드를 이용하며, 해당 메소드는 Body에 데이터를 넣지 않는다.

 

vscode: 상기 get, update와 같은 클래스이다.

 
    def delete(self, recipe_id) :

        # 디비 업데이트 실행코드
        try :
            # 데이터 삭제
            # 1. DB에 연결
            connection = get_connection()

            # 2. 쿼리문 만들기
            query = '''delete from recipe
                    where id = %s;'''
           
            record = (recipe_id, )

            # 3. 커서를 가져온다.
            cursor = connection.cursor()

            # 4. 쿼리문을 커서를 이용해서 실행한다.
            cursor.execute(query, record)

            # 5. 커넥션을 커밋해줘야 한다 
            connection.commit()

            # 6. 자원 해제
            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()
            return {'error' : str(e)}, 503

        return {'result':'success'},200

 

부가 설명 추가 포스팅:

https://yeo0616.tistory.com/171

https://yeo0616.tistory.com/172

https://yeo0616.tistory.com/173

 

반응형