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๊ฐ ๋ฌ๋ค. ์๋ฌ๊ฐ ๋ฌ๋ค๋ฉด ์ฝ๋์ ์คํ๊ฐ ์๋์ง ํ์ธํ์.