Rest API

API서버 - 클라이언트에서 입력받은 값으로 DB 수정하기 (PUT)

왕현성 2023. 1. 4. 17:36
728x90
from flask import Flask
from flask_restful import Api
from config import Config

from resources.recipe import RecipeListResource

app = Flask(__name__)
# 환경변수 셋팅
app.config.from_object(Config)

api = Api(app)

# 경로와 리소스(API코드)를 연결한다.
api.add_resource(RecipeListResource, '/recipes')

if __name__ == '__main__' :
    app.run()

메인 화면인 app.py의 코드는 이렇게 작성되어 있습니다.

 

DB의 값을 클라이언트로부터 입력받은 값으로 수정하는 코드(PUT)는 다음과 같습니다.

 

class RecipeResource(Resource) :

    def put(self, recipe_id) : 

        data = request.get_json()

        try : 
            connection = get_connection()
            query = '''update recipe
                    set
                    name = %s,
                    description = %s,
                    num_of_servings = %s,
                    cook_time = %s,
                    directions = %s
                    where id = %s;'''
            
            record = (data['name'],data['description'],data['num_of_servings'],data['cook_time'],data['directions'],recipe_id)

            cursor = connection.cursor()

            cursor.execute(query, record)

            connection.commit()

            cursor.close()
            connection.close()

        except Error as e :
            print(e)
            cursor.close()
            connection.close()
            return {'result' : 'fail', 'error' : str(e)}, 500

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

포스트맨에서 확인.

 

MySQL에서 확인.