Api 개발/flask

사진과 내용을 동시에 올리는 api

공부짱짱열심히하기 2023. 1. 13. 11:49

사진과 내용을 올리면,db에 저장

 

샘플테이블

posting

- id

-content

imgul

post posting

form-data

- photo

-content

 

 

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

 

워크벤치에서 연습하고 쿼리문 작성

        imgUrl = Config.S3_LOCATION + new_file_name

        #4.db에 저장한다

        try : 
            connection = get_connection()
            query = '''  insert into
                        posting
                        (content,imgUrl)
                        values
                        (%s,%s);   '''

 

확인

insert into
posting
(content,imgUrl)
values
('경치좋음','https://abc.com');

select * from posting;

 

class PostinfResource(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

데이터베이스에 잘들어와 있음

 

만약 사진외에 다른파일 들어왔을때 거절하는 방법

먼저 하드 코딩된 부분 수정

new_file_name = current_time.isoformat().replace(':' , '_' ) + '.' + file.content_type.split('/')[-1]

jpg로 고정하지 않고 본인의 타입을 그대로 받을 수 있게 

 

사진외에 다른파일을 send시

s3에 저장된내용

워크벤치안

 

이렇게 표현이됨

        if file.content_type.split('/')[0] != 'image' :
            return {'error': '사진만 올리세요'}
            
            
      	if 'image' not in file.content_type :
        	return {'error': '사진만 올리세요'}

아무거나 해도됨