728x90
- 해당 기능만을 서술한 포스팅으로, 전체 기능에 대한 소스 코드 확인은 이전 포스팅 글에서 확인 가능합니다.
https://hyunsungstory.tistory.com/204
이번엔, 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 |