1. 먼저 에러를 import 해준다
다음의 사이트를 참고하였다.
flask_jwt_extended.jwt_manager — flask-jwt-extended 4.4.4 documentation
flask-jwt-extended.readthedocs.io
from flask_jwt_extended.exceptions import RevokedTokenError
2. 사전형태로 처리하고싶은 에러들을 정리해준다. (이건 참고한 사이트 예시)
CUSTOM_ERRORS = {
'RoomDoesNotExist': {
'message': "A room by that name does not exist.",
'status': 404,
},
}
3. api 생성시 파라미터로 넣어준다.
api = Api(app, errors=CUSTOM_ERRORS)
전체코드
from flask import Flask, request
from flask.json import jsonify
from flask_restful import Api
from flask_jwt_extended import JWTManager
from flask_jwt_extended.exceptions import RevokedTokenError
from http import HTTPStatus
from config import Config
# resource 클래스 import
from resources.register import UserRegisterResource
from resources.logout import LogoutResource
from resources.blocklist import check_blocklist
app = Flask(__name__)
# 환경 변수 세팅
app.config.from_object(Config)
# JWT 토큰 만들기
jwt = JWTManager(app)
# 로그아웃한 유저인지 확인하는 코드는 생략
# catch 하고싶은 에러
CUSTOM_ERRORS = {
'RevokedTokenError': {
'message': "이미 로그아웃 되었습니다(401 Unauthorized).", 'status' : 401
},
}
# api = Api(app)
api = Api(app, errors=CUSTOM_ERRORS)
# resources 와 연결
api.add_resource(UserRegisterResource, '/v1/user/register')
api.add_resource(LogoutResource, '/v1/user/logout')
if __name__ == "__main__" :
app.run()
수정 전
수정 후
참고자료
https://flask-restful.readthedocs.io/en/latest/api.html?highlight=api#id1
API Docs — Flask-RESTful 0.3.8 documentation
Parameters: name – Either a name or a list of option strings, e.g. foo or -f, –foo. default – The value produced if the argument is absent from the request. dest – The name of the attribute to be added to the object returned by parse_args(). requir
flask-restful.readthedocs.io
(Api 의 파라미터를 확인하였다.
- errors () – A dictionary to define a custom response for each exception or error raised during a request
)
https://github.com/vimalloc/flask-jwt-extended/issues/141
Integration with flask-restful & error handling · Issue #141 · vimalloc/flask-jwt-extended
Similar to #86, errors like SignatureExpiry are returning 500 rather than 4xx errors. However I am using flask-restful which does not have an error_handler, so the solutions in the referenced issue...
github.com
(전체적인 방법 및 해결방법을 참고하였다.)
'Framework > 플라스크(flask)' 카테고리의 다른 글
requests 에서 파라미터 가져오는 함수 (args/ arg.get) 차이 (0) | 2022.10.03 |
---|---|
flask , 폼테이터 업로드하기, 파일 업로드 (form-data upload, file upload) (0) | 2022.09.27 |
로컬에서 플라스크 2개 동시에 실행하기 (0) | 2022.09.14 |
flask 에서 jwt 만료 안되게, 만료 시간(expires time) 설정하기 (0) | 2022.09.11 |
플라스크 서버를 개발환경으로 실행하기 (0) | 2022.01.25 |