왕현성
코딩발자취
왕현성
전체 방문자
오늘
어제
  • 코딩 (277)
    • Python (71)
    • Java (16)
    • MySQL (34)
    • 인공지능 (48)
      • 머신러닝 (16)
      • 딥러닝 (32)
    • 영상처리 (4)
    • Rest API (21)
    • Android Studio (25)
    • streamlit (13)
    • DevOps (22)
      • AWS (9)
      • PuTTY (5)
      • Git (4)
      • Serverless (2)
      • Docker (2)
    • IT 기술 용어 (6)
    • 디버깅 ( 오류 해결 과정 ) (17)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 영상처리
  • ckpt_file
  • matplotlib
  • 영상기술
  • get_long_description
  • UnboundLocalError
  • 영상처리역사
  • ComputerVision
  • labelme
  • tune()
  • 기상탐사
  • 비지도학습
  • 컴퓨터비전
  • imageprocessing
  • labelme UnocodeDecodeError
  • unsupervised
  • encoding='utf-8'
  • maskimage
  • OpenCV
  • alibi-detection
  • 의료이미징
  • pip install labelme
  • alibidetect
  • TensorFlow
  • 딥러닝
  • PYTHON
  • yolov8
  • pytorch
  • PIL
  • numpy

최근 댓글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
왕현성

코딩발자취

API - 클라이언트로부터 특정 정보의 값 출력하기 (GET)
Rest API

API - 클라이언트로부터 특정 정보의 값 출력하기 (GET)

2023. 1. 4. 13:54
728x90

 

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

from resources.recipe import RecipeListResource

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

api = Api(app)

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

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

메인 화면인 app.py의 코드는 이렇게 작성되어 있습니다.

 

DB의 값을 클라이언트로부터 특정 정보의 값을 출력하는 코드(get)는 다음과 같습니다.

 

각 코드마다 주석처리가 되어있습니다.

 

    def get(self) :
        # 1. 클라이언트로부터 데이터를 받아온다.
        # 없다.

        # 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 = i+1




            cursor.close()
            connection.close()
        except Error as e :
            print(e)
            cursor.close()
            connection.close()
            return{"result":"fail","error":str(e)}, 500
        
        return {"result" : 'seccess','items':result_list,'count':len(result_list)}, 200

 

포스트맨으로 확인하면 아래 사진과 같다.

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

API서버 - 클라이언트가 원하는 값 삭제하기 (DELETE)  (0) 2023.01.04
API서버 - 클라이언트에서 입력받은 값으로 DB 수정하기 (PUT)  (0) 2023.01.04
API - Python으로 DB에 값 넣기 (POST)  (0) 2023.01.04
Python에서 MySQL연동하는 방법 중에 Config파일을 만들어 정보를 따로 저장하는 방법  (0) 2023.01.04
Rest API 서버 개발을 위한 가상환경 설정과 flask 프레임워크 설치  (0) 2023.01.03
    'Rest API' 카테고리의 다른 글
    • API서버 - 클라이언트가 원하는 값 삭제하기 (DELETE)
    • API서버 - 클라이언트에서 입력받은 값으로 DB 수정하기 (PUT)
    • API - Python으로 DB에 값 넣기 (POST)
    • Python에서 MySQL연동하는 방법 중에 Config파일을 만들어 정보를 따로 저장하는 방법
    왕현성
    왕현성
    AI 머신비전 학습일지

    티스토리툴바