오늘 배운 것

오늘은 원래는 알람 이슈를 개발해보려고 했다. 그러나 개발 서버에서 모종의 이유로 오류가 나고 있었다. 오류를 보니 미들웨어 단에서 에러가 나는 것으로 보였다. 

 

구체적인 로그를 보니 'rest_framework'와 'JWTAuthentication'이 로그에 보였다. 아마도 관련 authentication backend 또는 middleware에서 나는 오류일 것이라고 추측했다. 로그를 자세히 보니 예상대로 JwtAuthentication에서 나는 오류였다. 정확히는 이를 상속받아 직접 만든 CustomJwtAuthentication에서 나는 오류였다. 

 

원인은 예외 케이스 처리를 해주지 않아서 생긴 오류였다. 기존 코드와 수정된 코드는 다음과 같다. 

# 기존 코드
class CustomJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        raw_token = self.get_raw_token(self.get_header(request))
        if raw_token is None:
            return None
# 수정된 코드
class CustomJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        header = self.get_header(request)
        if header is None:
            return None
        raw_token = self.get_raw_token(header)
        if raw_token is None:
            return None

 

self.get_header()에서 header 값이 None이 나오는 경우에 대해서 예외 케이스를 처리해주지 않은 것이 오류의 원인이었다. 이 부분을 해결해 주었더니 문제 페이지가 잘 나왔다. 


이제 어제 막혔던 알림 기능을 마저 개발해 보자. 어제의 결론은 미들웨어를 써서 문제를 해결하는 것이었는데, 막상 멘토님들께 이를 공유드리니 굳이 미들웨어를 사용할 필요는 없다는 피드백을 주셨다. 미들웨어는 모든 요청에서 공통으로 사용되는 로직, 가령 로깅이나 보안, 인증 관련해서 사용하는 것이 더 일반적이기 때문이었다. 

 

그래서 우선은 뷰 로직 맨 끝에다가 FCM 함수 호출로직을 추가하는 것으로 해 보았다. 우선 다음과 같이 공통 알림 로직을 만들어 주었다. 

def send_push_notification_device(token, target_user, title, body):
    target_device = FCMDevice.objects.filter(user=target_user).exclude(registration_id=token)
    if target_device.exists():
        target_device = target_device.first()
        try:
            target_device.send_message(
                messaging.Message(
                    notification=messaging.Notification(
                        title=title,
                        body=body,
                    ),
                )
            )
        except Exception:
            pass

 

그리고 필요한 views 파일에서 해당 로직을 호출해 주는 식으로 변경하였다. 

 

+ Recent posts