RestFul API

RestFul API에서 POST하기(클라이언트가 데이터 입력하면 DB에 저장하기) : mysql_connection와 config 파일 만들기

567Rabbit 2024. 5. 20. 17:12

DB 설계하기

 

코드 입력하고 실행하기 (비밀번호 부분 수정해서 입력한다)

-- recipe_db 에만 전용으로 접속할 수 있는 계정을 만들어야 한다

use mysql;
create user 'recipe_db_user'@'%' identified by '비밀번호 자유롭게 설정한다';
grant ALL privileges on recipe_db.* to 'recipe_db_user'@'%';

 

 

 

aws 엔드포인트 복사

 

 

 

 

 

MySQL Hostname에 붙여넣기

 

 

 

비밀번호는 앞전에 설정한대로 입력하기

 

 

 

 

 

 

DB로 들어가 recipe Table을 만든다

 

 

 

 

 

 

 

Postman 실행하기

 

New -> collection 해도 되고, +모양을 눌러서 Blanck collection 해도 된다.

 

 

 

 

 

...  눌러서 Add request

 

 

 

 

 

 

 

Body에 Data를 입력해야 하므로 Body 클릭

 

 

 

 

 

raw(원본 데이터)로 설정하고 데이터 입력 후 저장, 데이터는 json 형식으로 작성함

- json 형식은 "큰따옴표"만 사용한다

 

 

 

 

 

 

VSCode

 

VScode에 app.py 파일 만들고 기본 API 만들기

 

 

 

 

 

 

app.py 작성

 

 

 

 

 

recipe.py 작성

- 컬럼에 대해 매칭되는 변수는 %s로 한다

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

class RecipeListResource(Resource) :
    
    def post(self) :
        
        # 1. 클라이언트가 보내준 데이터가 있으면 그 데이터를 받아준다.
        data = request.get_json()
        
        # 2. 이 정보를 DB에 저장한다.
        try :
            ### 1. DB에 연결
            connection = get_connection()
            
            ### 2. 쿼리문 만들기
            query = '''insert into recipe (name, description, num_of_servings, cook_time, directions) values ( %s , %s , %s , %s , %s);'''
            
            ### 3. 쿼리에 매칭되는 변수 처리 \
            record = (data['name'],data['description'],data['num_of_servings'],data['cook_time'],data['directions']) 
            
            ### 4. 커서를 가져온다
            cursor = connection.cursor()
            
            ### 5. 쿼리문을 커서로 실행한다
            cursor.execute(query, record)
            
            ### 6. DB에 완전히 반영하기 위해서는 commit한다 안하면 rollback됨
            connection.commit()
            
            ### 7. 자원 해제
            cursor.close()
            connection.close()
            
        except Error as e : 
            if cursor is not None :  # null이 아니면
                cursor.close()
            if connection is not None :
                connection.close()
            return {'result' : 'fail' , 'error' : str(e) } , 500  # 500 에러
        
        return { 'result' : 'success' } , 200 # 200은 디폴트값이므로 안써도 됨

 

 

 

 

mysql_connection.py 작성

 

- vscode cmd에 connector 설치 

pip install mysql-connector-python

 

 

 

 

config.py 작성

 

 

 

 

 

컨트롤+s로 파일 저장시키고, flask run 하기

 

 

 

 

이 화면이 뜨지 않으면 파일 저장을 했는지 확인하자

 

 

 

 

 

 

 

다시 Postman으로 돌아와 Send를 누르면 success가 뜬다. 에러가 뜬다면 코드에 오타가 있는지 확인하자.