왕현성
코딩발자취
왕현성
전체 방문자
오늘
어제
  • 코딩 (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)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

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

코딩발자취

AmazonRekognition을 사용하여 객체탐지(Object detection) / 사진과 문장을 업로드하는 SNS의 Posting API 개발
Rest API

AmazonRekognition을 사용하여 객체탐지(Object detection) / 사진과 문장을 업로드하는 SNS의 Posting API 개발

2023. 1. 13. 11:19
728x90
  • 해당 기능만을 서술한 포스팅으로, 전체 기능에 대한 소스 코드 확인은 이전 포스팅 글에서 확인 가능합니다.
    https://hyunsungstory.tistory.com/204
 

AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발

Amazon Rekognition란? Amazon Rekognition Rekognition을 사용하면 애플리케이션에 이미지 및 비디오 분석을 쉽게 추가할 수 있습니다. Amazon Rekognition API에 이미지나 비디오를 제공하면 서비스에서 객체, 사람

hyunsungstory.tistory.com

 

이번엔, DB와 연동하여 샘플 테이블을 만들고

 

사진과 문장을 body 부분의 form-data로 받고

 

사진은 유니크한 파일명으로 S3에 저장하고 imgUrl을 만들어 DB에 저장 / 문장( 게시글 포스팅 내용 )도 DB에 저장하는 코드를 작성을 해보겠다.

 

1. MySQL 테이블 생성

2. API 설계

3. Visual Stuodio Code 작성

from flask import request
from flask_restful import Resource
from flask_jwt_extended import create_access_token,jwt_required,get_jwt
from flask_jwt_extended import create_access_token,jwt_required,get_jwt
from mysql.connector import Error
from mysql_connection import get_connection
from datetime import datetime
import boto3
from config import Config

class PostingResource(Resource) :

    def post(self) :

        # 1. 클라이언트로부터 데이터를 받아온다.
        # form-data
        # photo : file
        # content : text

        # 사진과 내용은 필수항목이다!!
        if 'photo' not in request.files or 'content' not in request.form :
            return {'error':'데이터를 정확히 보내세요.'},400
        
        file=request.files['photo']
        content=request.form['content']

        # 2. 사진을 먼저 S3에 저장한다.

        # 파일명을 유니크하게 만드는 방법
        current_time=datetime.now()
        new_file_name=current_time.isoformat().replace(':','_') + '.jpg'

        print(new_file_name)

        # 파일명을, 유니크한 이름으로 변경한다.
        # 클라이언트에서 보낸 파일명을 대체!

        file.filename = new_file_name

        # S3에 파일을 업로드하면 된다.
        # S3에 파일 업로드하는 라이브러리가 필요
        # boto3 라이브러리를 이용해서 업로드한다.
        # 참고 : 라이브러리 설치는 pip install boto3

        client=boto3.client('s3',
                    aws_access_key_id = Config.ACCESS_KEY ,
                    aws_secret_access_key = Config.SECRET_ACCESS)
        
        try :
            client.upload_fileobj(file,Config.S3_BUCKET,new_file_name,
                                    ExtraArgs ={'ACL':'public-read','ContentType':file.content_type})
        
        except Exception as e :
            return {'error':str(e)}, 500

        #3. 저장된 사진의 imgUrl을 만든다.
        imgUrl = Config.S3_LOCATION+new_file_name
        # 4. DB에 저장한다.
        try :
            connection = get_connection()
            query='''insert into
                    posting
                    (content,imgUrl)
                    values
                    (%s,%s);'''
            record = (content,imgUrl)
            cursor = connection.cursor()
            cursor.execute(query,record)
            connection.commit()
            cursor.close()
            connection.close()

        except Error as e :
            print(e)
            cursor.close()
            connection.close()
            return{'error':str(e)},500
        
        return {'result':'success'},200

4. 테스트 결과

정상 작동하는 것을 확인할 수 있다.

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

AWS Rekognition 얼굴비교, 이미지 내 텍스트 추출하기  (0) 2023.02.21
Naver Open API - 뉴스 검색 API , 파파고 번역 API 사용하기  (0) 2023.01.13
AmazonRekognition을 사용하여 객체탐지(Object detection) / 자동 태그 API 개발  (0) 2023.01.13
AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발  (0) 2023.01.12
API 서버 - 로그인한 회원과 비회원 구분하여 시스템 개발하기 // jwt_required(optional= )  (0) 2023.01.10
    'Rest API' 카테고리의 다른 글
    • AWS Rekognition 얼굴비교, 이미지 내 텍스트 추출하기
    • Naver Open API - 뉴스 검색 API , 파파고 번역 API 사용하기
    • AmazonRekognition을 사용하여 객체탐지(Object detection) / 자동 태그 API 개발
    • AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발
    왕현성
    왕현성
    AI 머신비전 학습일지

    티스토리툴바