개발학습일지

[Restfull API] Python에서 MySQL Connector select 하는 방법 본문

Restful API

[Restfull API] Python에서 MySQL Connector select 하는 방법

처카푸 2024. 5. 21. 18:03

Python에서 MySQL Connector select 하는 방법 _개발 흐름 느끼기

 

1. Postman 준비

- Postman을 실행시킨다.
- add request를 눌러 새로운 API를 시작한다.
- HTTP method 는 새로운 데이터를 가져올(select) 것이기 때문에 GET로 설정,
- 나의 로컬호스트 번호를 적고 경로를 적어준다.

- 가져오는 데이터를 페이징 처리 해준다. _파라미터에 입력 쿼리 스트링 자리에 자동으로 입력된다

selct

2. app.py 에 경로와 리소스를 연결, Entry point에 경로 작성하기

- 경로만 정해뒀기 때문에 경로만 우선 작성

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

 

3. 리소스 폴더에 API 만들기

- class 리소스 만들고, app.py에 리소스 이름 적어주기

- 함수에 http 메소드 get 사용한다.

class RecipeListResource(Resource):
    def get(self) :
    	return

 

4. 함수 안에 로직 만들기

- 큰 틀 : 클라이언트가 보낸 데이터 받기 -> DB에 저장하기 -> 클라이언트한테 JSON형식으로 응답하기

- DB에 저장하기 : DB연결 -> 퀴리문 만들기 -> 커서를 가져온다 -> 쿼리문 커서로 실행  -> 자원 해제하기

    def get(self) :
        
        # 1. 클라이언트가 보낸 데이터가 있으면 받아준다.
        offset = request.args['offset']
        limit = request.args['limit']

        print(offset, limit)

        # 2. DB로 부터 데이터를 가져온다.
        try : 
            connection = get_connection()
            
            # 문자열 더하라는 뜻 '''+data변수명+'''
            query = '''
                    select *
                    from recipe
                    limit '''+offset+''', '''+limit+''';
                    '''
            
            # 쿼리안에 변수를 직접 써서 record = () 는 없다
			
            # dictionary=True
            cursor = connection.cursor(dictionary=True)

            cursor.execute( query )

            # 데이터를 가져와야한다.
            result_list = cursor.fetchall()

            # 튜플로는 보낼수 없다 그래서 커서에 dictionary=True 추가
            print(result_list)

            cursor.close()
            connection.close()

        except Error as e:
            # try에서 에러가 발생하면 클라이언트한테 리턴해준다.
            # json 은 숫자 아니면 문자열만 있다!!!
            if cursor is not None :
                cursor.close()
            if connection is not None :
                connection.close()
            return {'result':'fail', 'error':str(e)}, 500

        # 3. 클라이언트에게 json 형식으로 응답한다.
        # JSON 형식으로 보내기 위해서 데이터에 있는 datetime 형식을 isofomat해준다.
        # 반복문으로 리스트 안에 있는 모든 데이터를 변경한다.
        i = 0
        for row in result_list :
            result_list[i]['created_at']= row['created_at'].isoformat()
            result_list[i]['updated_at']= row['updated_at'].isoformat()
            i = i + 1

        print()
        print(result_list)

        return {'items' : result_list,
                'count' : len(result_list),
                'result' : 'success'}

 

5. 코드 작성이 완료되면,

- 서버 실행  $ flask run

- 포스트맨에서 Send를 클릭해 하단의 정보를 확인하고 상태코드 200 OK 인지 확인한다.

잘 보여주는 확인하기

 

+ 1개 데이터만 가져오는 코드!!

- 1개만 가져오는 것이기 때문에 새로운 경로와 클래스를 만들고 시작한다.

- app.py 에 api.add_resource( 클래스이름, 경로 ) 만들기

- 리소스 폴더의 파일에서, 새로운 클래스에 함수 get 작성한다.

    def get(self, recipe_id) :
        
        # 1. 클라이언트로부터 데이터를 받는다.
        print(recipe_id)

        # 2. DB 로 부터 데이터 가져오기
        try : 
            connection = get_connection()

            print('커넥션 실행')
            
            # 쿼리문 달라졌다
            query = '''
                    select *
                    from recipe
                    where id = %s ;
                    '''
            
            # 튜플은 값이 한개여도 콤마가 있어야한다
            recode = (recipe_id, )
            
            print(recode)

            cursor = connection.cursor(dictionary=True)

            print('커서 가져오기 성공')

            cursor.execute( query , recode )
			
            # 프린트 하면서 오류 확인하는 디버깅 방법 
            print('쿼리문 실행')

            # 데이터를 가져와야한다.
            result_list = cursor.fetchall()

            # 튜플로는 보낼수 없다 그래서 커서에 dictionary=True 추가
            print(result_list)

            cursor.close()
            connection.close()

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


        # 3. 응답 할 데이터를 JSON으로 만든다. 
        i = 0
        for row in result_list :
            result_list[i]['created_at']= row['created_at'].isoformat()
            result_list[i]['updated_at']= row['updated_at'].isoformat()
            i = i + 1
        
        # 없는 id 를 입력할 경우 오류를 클라이언트에게 보여준다
        if len(result_list) == 1 :
            return {"items" : result_list[0],
                    "result" : "success"}
        else :
            return {"result":"fail", 
                    "error":"해당 아이디는 존재하지 않습니다."}, 400

 

 

 


* 쿼리문 변수 작성

컬럼과 값이 동일한 위치 선상에 있으면   %s   쓰고 recode에 튜플 형태로 변수명 작성 _튜플의 기본상태 -> ( , )

문자열 변수를 넣어야 하면   '''+변수명+'''   사용

 

* 에러 코드 작성

숫자는 개발자 마음대로 넣는 것이지만 내용을 보고 알맞은 에러 코드를 작성해 주자.

디폴트 코드는 200 (정상)이다.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500

 

500 Internal Server Error - HTTP | MDN

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.

developer.mozilla.org

 

* cursor(dictionary=True)를 쓰는 이유

https://msdev-st.tistory.com/131

 

[Restfull API] TypeError : Object of type ... is not JSON serializable 에러가 발생한 이유와 해결 방법

TypeError : Object of type ... is not JSON serializable 에러가 발생한 이유와 해결 방법 문제 발생: DB에 있는 데이터를 서버에 select 하는 중," TypeError: Object of type datetime is not JSON serializable" 발생 

msdev-st.tistory.com