app.py파일이 실행파일이고 resources폴더안에 recipe.py와 recipe_info.py파일이 들어있다.

mysql_connection.py파일에는 mysql에 연결하기위한 코드들이 작성되어 있다.

 

app.py 코드

from flask import Flask
from flask_restful import Api

from resources.recipe import RecipeListResource
from resources.recipe_info import RecipeResource


app = Flask(__name__)

api = Api(app)

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

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

플라스크를 import하고 기본 구조 작성뒤 경로와 리소스를 연결한다.

 

recipe.py 코드

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

### API 를 만들기 위한 클래스 작성
### class(클래스) 란??  변수와 함수로 구성된 묶음!
### 클래스는 상속이 가능하다!
### API를 만들기 위한 클래스는, flask_restful 라이브러리의
### Resource 클래스를 상속해서 만들어야 한다.

class RecipeListResource(Resource):
    # restful api 의 method 에 해당하는 함수 작성
    def post(self) :
        # api 실행 코드를 여기에 작성

        # 클라이언트에서, body 부분에 작성한 json 을
        # 받아오는 코드
        data = request.get_json()

        # 받아온 데이터를 디비 저장하면 된다.
        try :
            # 데이터 insert 
            # 1. DB에 연결
            connection = get_connection()

            # 2. 쿼리문 만들기
            query = '''insert into recipe
                    (name, description, cook_time, directions)
                    values
                    ( %s , %s , %s ,%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

    def get(self) :
        # 쿼리 스트링으로 오는 데이터는 아래처럼 처리해준다.
        offset = request.args.get('offset')
        limit = request.args.get('limit')

        # 디비로부터 데이터를 받아서, 클라이언트에 보내준다.
        try :
            connection = get_connection()

            query = '''select *
                    from recipe
                    limit '''+offset+''' , '''+limit+''';'''
            
            # select 문은, dictionary = True 를 해준다.
            cursor = connection.cursor(dictionary = True)

            cursor.execute(query)

            # 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" , 
                "count" : len(result_list) ,
                "result_list" : result_list }, 200

insert와 select가 post, get 메소드로 구현되어있다. 

 

recipe_info.py 코드

from http import HTTPStatus
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):

        # 디비에서, 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 함수를 사용한다.
    def put(self, recipe_id):

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

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

            # 2. 쿼리문 만들기
            query = '''update recipe
                    set name = %s, description = %s,
                    cook_time = %s,
                    directions = %s
                    where id = %s;'''

            record = (data['name'], data['description'], data['cook_time'], data['directions'], 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':'sucess'}, 200

    # 삭제하는 delete 함수
    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

select, update, delete가 get, put, delete 메소드로 구현되어 있다.

Indexes에 들어가서 Index Name을 적고 Type을 FULLTEXT로 정한뒤 Index Columns에 원하는 문자열 컬럼을 정한다.

FULLTEXT 인덱스를 생성하면 검색의 속도도 높이고 검색 옵션도 다양하게 이용 할 수 있다.

unique한 컬럼에 중복된 값을 넣으면 에러가 난다.

애초에 중복된 값을 넣지 말던가, 아니면 중복된 값을 삭제하고 다시 넣으면 된다.

primary key또한 중복된 값을 허용하지 않는다.

첫 번째 방법은 테이블의 스패너 모양을 클릭해서 이 창에서 UQ를 체크하고 Apply하는 것이다.

 

두 번째 방법은 indexes에 들어가서 Index Name에 이름을 넣고 Type에 UNIQUE를 설정후 Index Columns에 원하는 컬럼을 선택하고 apply하는 것이다.

NULL인 데이터를 가져오는 방법

where 칼럼명 is NULL

 

NULL이 아닌 데이터를 가져오는 방법

where 칼럼명 is not NULL

customers 테이블
orders 테이블

각 고객별로 주문 금액 최대값이 600달러 이상인 데이터만 가져와서 내림차순으로 정렬하려고 한다.

이때 group by 뒤에는 where이 아니라 having을 써준다.

select c.first_name, c.last_name, max(o.amount) as MAX
from customers c
join orders o
	on c.id = o.customer_id
group by c.id having max(o.amount) >= 600
order by MAX desc;

customers 테이블
orders 테이블

100명의 고객과 700개의 주문으로 이루어진 두 개의 테이블이 있다.

두개 테이블의 교집합을 나타내려면

select *
from customers
join orders
	on customers.id = orders.customer_id;

모든 고객 데이터를 가져오되, 주문정보가 없는 고객도 나타나도록 가져오는 방법은 left join을 쓰면된다.

select *
from customers c
left join orders o
	on c.id = o.customer_id;

 

foreign key를 설정하면 참조하는 테이블에 이 연결된 키 값이 있는지 확인하고 없으면 데이터 저장이 안되도록 한다.

reviews라는 테이블에 reviewers와 series의 id를 참조하는 foreign key를 만든다.

위사진처럼 이름을 적고 참조하는 테이블을 선택하고 reviews의 컬럼을 고른뒤 참조할 컬럼을 고른다.

apply를 누르면 적용된다.

'AWS MySQL' 카테고리의 다른 글

MySQL group by의 having 사용법  (0) 2022.05.17
MySQL join과 left join 하는 방법과 예시  (0) 2022.05.17
MySQL ifnull함수 사용법  (0) 2022.05.17
MySQL IF함수  (0) 2022.05.17
MySQL CASE 문 작성법  (0) 2022.05.16

people 테이블

ifnull함수 컬럼의 null값을 다른 값으로 변경할 때 쓴다.

select *, ifnull(age, 100)
from people;

books 테이블

if함수 pages 가 300보다크면 long 아니면 short로 나오게 하고 싶다.

select *, if(pages >= 300, 'long', 'short')
from books;

 

+ Recent posts