Skip to content

Commit

Permalink
Feat : #24 api req/res수정
Browse files Browse the repository at this point in the history
  • Loading branch information
gilyeon00 committed Sep 29, 2022
1 parent 01128aa commit 6ebed16
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 72 deletions.
24 changes: 5 additions & 19 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,29 +147,15 @@ def post(self):
@ladder_api.route('/convert-image')
class ConvertImage(Resource):
def post(self):
# if not request.is_json:
# return jsonify({"msg": "Missing JSON in request"}), 400

# email = get_jwt_identity()
origin_image = request.files['file']
print('originImage request OK')

# email = request.json.get('email')
result_url = saveOriginImage(origin_image)
print("saveImage OK")

# header_request = request.headers
# bearer = header_request.get('Authorization')
# if not bearer:
# return {"error": "You don't have access authentication."}, 401
# access_token = bearer.split()[1]
# email = pyjwt.decode(access_token, app.config['JWT_SECRET_KEY'], 'HS256')['sub']
# print(email)
return result_url

originImage = request.files['file']
print('originImage request OK')

resultImage = saveOriginImage(originImage)
print("saveImage OK")
resp = jsonify(resultImage)
resp.status = 201
return resp

## Create user
@app.route('/create-user', methods=['POST'])
Expand Down
2 changes: 1 addition & 1 deletion config/ai_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# AI_SERVER_HOST=os.environ.get('AI_HOST')
# AI_SERVER_PORT=os.environ.get('AI_PORT')

AI_CONVERT_API=f'http://ai:5555/images/result'
AI_CONVERT_API=f'http://ai:5555/api/v1/converting-image'

# RABBITMQ_HOST=os.environ.get('RABBITMQ_HOST')
# RABBITMQ_PORT=os.environ.get('RABBITMQ_PORT')
Expand Down
6 changes: 3 additions & 3 deletions entity/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
db = flask_sqlalchemy.SQLAlchemy()

class User(db.Model):
__tablename__ = 'user'
__tablename__ = 'User'
user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
Expand All @@ -25,9 +25,9 @@ def check_password(self, password):


class Image(db.Model):
__tablename__ = 'image'
__tablename__ = 'Image'
image_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('User.user_id'), nullable=False)
origin_url = db.Column(db.String(200))
result_url = db.Column(db.String(200))
create_at = db.Column(db.DateTime, default=datetime.now)
Expand Down
6 changes: 5 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ flask_jwt_extended
flask_bcrypt
flask_restx
redis
requests
requests
pillow
pybase64
bytesbufio
matplotlib
2 changes: 1 addition & 1 deletion s3bucket/s3_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def s3_connection():
service_name = "s3",
region_name = "ap-northeast-2",
aws_access_key_id = "AKIAWLCHMQTOJFJOXENM",
aws_secret_access_key = ""
aws_secret_access_key = "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"
# secret key 넣고 사용해주세요
)
print("s3 bucket connected!1")
Expand Down
85 changes: 38 additions & 47 deletions service/image_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@

from s3bucket import s3_connect
from api import s3_api
from entity.model import Image
from entity import database
from entity.model import User, Image
from entity.model import db

import requests
from datetime import datetime as dt
Expand All @@ -15,6 +16,12 @@
import jwt as pyjwt
import redis

import base64
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt


secrets_key = 'Ladder_teamc'
jwt_redis = redis.StrictRedis(host='redis', port=6379, decode_responses=True)

Expand All @@ -26,38 +33,6 @@

# 사진 받아오는 함수
def saveOriginImage(file) :

# header_request = request.headers
# bearer = header_request.get('Authorization')

# # upload api for no login users
# if not bearer:
# email = "[email protected]"
# user_id = 999
# # postgres image table에 업로드
# origin_url = "https://ladder-s3-bucket.s3.ap-northeast-2.amazonaws.com/origin/"+origin_image_name
# origin_url = origin_url.replace(" ","/")
# database.add_instance(Image, user_id = user_id, origin_url = origin_url, is_deleted = False)

# return origin_url

# # upload api for login users
# access_token = bearer.split()[1]
# email = pyjwt.decode(access_token, secrets_key, 'HS256')['sub']

# # check signout user
# user_access_key = email + '_access'
# is_logout = jwt_redis.get(user_access_key)
# if is_logout:
# return {"msg": "This is a invalid user."}, 401

# 이메일 받아오면 user_id 찾기
# sql = f"SELECT user_id \
# FROM user \
# WHERE email='{email}'"
# cursor = database.session_execute(sql)
# user_id = cursor.fetchall()[0][0]

user_id = 1

# 파일 이름 지정
Expand All @@ -77,32 +52,45 @@ def saveOriginImage(file) :
# ai 셀러리 요청, 이제 요 다음부터 비동기처리
convertImage.delay(origin_url)

return origin_url



# celery가 처리할 거
# api요청 (ai 서버)
@app.task()
def convertImage(origin_url):
print("convertImage def : 11111111111")
headers = {'Content-Type': 'application/json; chearset=utf-8'}

req = {'img' : origin_url}
print("=========================================")
print(req)
# request : params = request.get_json()
# response : make_photo(params['img'])
result_image = requests.post(AI_CONVERT_API, req, timeout=5)

res = requests.post(AI_CONVERT_API,json=req)
result_json = res.json()
print("convertImage def : 333333333333")
#result_image.request.get_file()
saveResultImage(result_image)
# result_url type : <class 'requests.models.Response'>

# image_dict = {
# "converted_image_name": file_name,
# "converted_image.png": encoded_string.decode()
# }

converted_image_name = result_json['converted_image_name']
converted_image = result_json['converted_image.png']
converted_image = converted_image.open(BytesIO(base64.b64decode(base64_string)))

print("===============app.task finish====================s")
print("===============app.task finish====================s")
print("===============app.task finish====================s")
print(converted_image_name)

result_url = saveResultImage(converted_image)
print(result_url)
print("===============app.task finish====================s")

return result_url



# 변환된 사진 저장
def saveResultImage(file) :

print("filename================")
# AttributeError: 'Response' object has no attribute 'filename'
# AttributeError: 'bytes' object has no attribute 'filename'
user_id =1
# 파일 이름 지정
filename = file.filename.split('.')[0]
Expand All @@ -116,8 +104,11 @@ def saveResultImage(file) :
# postgres image table에 origin_url 업로드
result_url = "https://ladder-s3-bucket.s3.ap-northeast-2.amazonaws.com/result/"+result_image_name
result_url = result_url.replace(" ","/")

database.add_instance(Image, user_id = user_id, result_url = result_url, is_deleted = False)

print("성공적으로 변환된 사진이 S3에 저장되었습니다.")

return result_url


0 comments on commit 6ebed16

Please sign in to comment.