드레:
코딩 뿌시기
드레:
전체 방문자
오늘
어제
  • 분류 전체보기 (268)
    • Python (74)
      • Python 기초 (42)
      • Numpy (8)
      • Pandas (22)
    • Machine Learning (31)
      • Machine Learning (1)
      • Deep Learning (27)
    • AWS (22)
      • RDS (3)
      • EC2 (9)
      • Lambda (8)
      • S3 (2)
    • MySQL (24)
    • Git (8)
    • Streamlit (12)
    • REST API (22)
    • Java (24)
    • Android (36)
    • Debugging (15)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • serverless
  • volley
  • 딥러닝
  • 네이버 API
  • Ann
  • AWS
  • Retrofit2
  • Transfer Learning
  • 액션바
  • JWT
  • Callback
  • tensorflow
  • Python
  • AWS Lambda
  • 안드로이드 스튜디오
  • CNN
  • Java
  • Lambda
  • pandas
  • flask
  • Streamlit
  • GET
  • 깃이그노어
  • API
  • fine tuning
  • github
  • aws s3
  • EC2
  • 서버리스
  • rest api

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
드레:

코딩 뿌시기

API서버 - Python MySQL Connector를 이용해 select하기(GET 메소드)
REST API

API서버 - Python MySQL Connector를 이용해 select하기(GET 메소드)

2023. 1. 4. 19:38

mysql_connection.py 파일

# MySQL에 접속하는 함수
import mysql.connector

from config import Config 

def get_connection():

    connection = mysql.connector.connect(
        host= Config.HOST,
        database= Config.DATABASE,
        user= Config.DB_USER,
        password= Config.DB_PASSWORD
    )
    return connection

 

 

API 리소스를 관리하는 recipe.py 파일

class RecipeListResource(Resource) :

    # GET 메소드를 처리하는 함수
    def get(self):

        # 1. 클라이언트로부터 데이터를 받아온다.
        #    get은 받아오는 데이터 없다!!!

        # 2. DB에 저장된 데이터를 가져온다.
        try :
            connection = get_connection()

            query = '''select *
                    from recipe;'''

            ### 중요!!! 
            # select 문은 커서 가져올때, dictionary=True로 해준다.
            cursor = connection.cursor(dictionary=True)
            cursor.execute(query)
            result_list = cursor.fetchall()
            # print(result_list)

            ### 중요!!!
            # DB에서 가져온 timestamp는 파이썬에서 datetime으로 자동 변환된다.
            # 문제는, 우리는 json으로 클라이언트한테 데이터를 보내줘야 하는데
            # datetime은 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 += 1

            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()

            return {"result" : "fail", "error" : str(e)}, 500
        
        return {"result" : "success",
                "items" : result_list,
                "count" : len(result_list)}, 200

 

 

메인파일 app.py

from flask import Flask
from flask_restful import Api
from config import Config

from resources.recipe import RecipeListResource, RecipeResource, RecipePublishResource
from resources.user import UserRegisterResource



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

api = Api(app)

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

api.add_resource(UserRegisterResource, '/user/register')


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

 

 

포스트맨에서 테스트

정상적으로 데이터를 가져온다.

'REST API' 카테고리의 다른 글

API서버 - Python MySQL Connector를 이용해 delete하기(DELETE 메소드)  (0) 2023.01.04
API서버 - Python MySQL Connector를 이용해 update하기(PUT 메소드)  (0) 2023.01.04
API서버 - Python MySQL Connector를 이용해 insert하기(POST 메소드)  (0) 2023.01.04
Python Flask를 사용한 REST API서버 개발방법  (0) 2023.01.04
API 서버 개발환경 구축 - python 가상환경, 필요한 라이브러리 설치  (0) 2023.01.04
    'REST API' 카테고리의 다른 글
    • API서버 - Python MySQL Connector를 이용해 delete하기(DELETE 메소드)
    • API서버 - Python MySQL Connector를 이용해 update하기(PUT 메소드)
    • API서버 - Python MySQL Connector를 이용해 insert하기(POST 메소드)
    • Python Flask를 사용한 REST API서버 개발방법
    드레:
    드레:

    티스토리툴바