ImageUs-상태코드 클래스

codakcodak·2023년 2월 27일
0

ImageUs

목록 보기
6/17
post-thumbnail

문제상황

  • 각각의 route에서 상태코드를 내보낼 때,스웨거의 상태코드를 명시할 때 하드코딩으로 한다면 추후 상태코드와 설명을 변경할 때 시간이 소모된다.

해결방법

  • 스웨거의 response와 route의 response로 내보낼 상태코드와 메세지를 미리 저장하고 모델을 생성하는 클래스 선언

적용과정

1.클래스 생성

tool/api.py

class ApiError:
    errors={
        'email_existance_sign_up_error':{
            'message':"이메일이 이미 존재합니다.",
            'status_code':402
        },
        'email_existance_login_error':{
            'message':"이메일이 존재하지 않습니다.",
            'status_code':404
        },
        'user_existance_error':{
            'message':"해당 유저가 존재하지 않습니다.",
            'status_code':404
        }
    }
    
    def __init__(self,api):
        self.api=api
        
    def email_existance_sign_up_error(self):
        return self.errors['email_existance_sign_up_error']
    
    def email_existance_sign_up_error_model(self):
        return self.api.model('email_existance_sign_up_error_model',{'message':fields.String(self.errors['email_existance_sign_up_error']['message'])})
    
    def email_existance_login_error(self):
        return self.errors['email_existance_login_error']
    
    def email_existance_login_error_model(self):
        return self.api.model('email_existance_login_error_model',{'message':fields.String(self.errors['email_existance_login_error']['message'])})

*errors애 모든 라우터에서 공통적으로 쓸 에러코드와 메세지가 담긴 클래스 변수를 저장

*init_은 클래스 생성 시 전달받은 api 클래스를 인스턴수 변수로 저장

*클래스 변수와 스웨거의 response_model을 명시할 model를 반환하는 메서드 작성

2.라우터 파일에서 클래스 생성

user_namespace=Namespace('user',description='유저의 정보를 생성,호출,수정,삭제 합니다.')

def user_router(api,services,config,es):
    user_service=services.user_service
    image_service=services.image_service
    room_service=services.room_service

    api.add_namespace(user_namespace,'')
    
    api_error=ApiError(user_namespace)

*api_error에 user_namespace라는 스웨거의 api클래스를 기준으로 에러코드들을 저장

3.route에서 return과 스웨거의 response의 인자에 명시

@user_namespace.route("/auth")
class email_auth(Resource):
        @user_namespace.expect(get_user_email_auth_parser,validate=False)
        @user_namespace.response(200,"1 send mail success")
        @user_namespace.response(api_error.user_search_no_arg_error()['status_code'],
                                 '해당 필드가 없습니다.',
                                 api_error.user_search_no_arg_error_model())
        @user_namespace.response(api_error.user_email_existance_auth_error()['status_code'],
                                 '해당 필드가 없습니다.',
                                 api_error.user_email_existance_auth_error_model())
        def get(self):
            '''
            유저의 이메일 인증 문자를 발송합니다.
            '''
            if 'email' not in request.args:
                print(api_error.user_search_no_arg_error()['message'])
                return make_response(jsonify({'message':api_error.user_search_no_arg_error()['message']}),
                                     api_error.user_search_no_arg_error()['status_code'])
            email=request.args['email']
            print(email)
            if user_service.is_email_exists(email):
                return make_response(jsonify({'message':api_error.user_email_existance_auth_error()['message']}),
                                     api_error.user_email_existance_auth_error()['status_code'])
            
            auth_password=user_service.generate_auth_password()

            if user_service.get_email_auth_info(email):
                user_service.initiate_email_auth(email,auth_password)

            else:
                user_service.create_new_email_auth(email,auth_password)

            send_result=user_service.send_email_auth_password(email,auth_password)

            return make_response(jsonify({'result':f'{send_result} send mail success'}))

결과

  • 상태코드에 대한 변경이 이루어 진다면 선언한 클래스에서 메세지와 상태코드만 변경해주면 모든 반환형에 적용 가능
profile
숲을 보는 코더

0개의 댓글