Microservice with django

i tried turning an old project to see if i make it work as microservices
it is a chat application

i separated them into two

  1. auth service(which handles registration, login, contacts and emails)
  2. chat service (which handles chatting with contacts)

the auth service works perfectly
but i am having issues in the chat service first let me send the models

class Message(models.Model):
    sender_id = models.IntegerField()  # Store user IDs instead of foreign keys
    receiver_id = models.IntegerField()
    message = models.TextField()
    timestamp = models.DateTimeField(default=timezone.now)
    is_read = models.BooleanField(default=False)

    def __str__(self):
        return f"Message from {self.sender_id} to {self.receiver_id} at {self.timestamp}"

since i cannot reference foreign key i am using integerfield

i also made a custom middleware that verifies the token entered when th chat endpoint is called

class SimpleUser:
    def __init__(self, user_id, email, full_name, is_active):
        self.id = user_id
        self.email = email
        self.full_name = full_name
        self.is_active = is_active

    
    @property
    def is_authenticated(self):
        return True
    
    
    @property
    def is_anonymous(self):
        return False 
    
    def __str__(self):
        return f"{self.full_name} ({self.email})"



class AuthenticateJWTMiddleware:
    
    AUTH_SERVICE_URL = "http://127.0.0.1:8800/api/auth/verify_token/"
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    
    def __call__(self, request):
        if request.path.startswith('/admin/'):
            return self.get_response(request)
        
        self.process_request(request)
        response = self.get_response(request)
        return response
    
    
    def process_request(self, request):
        print(f"Middleware Processing: Path={request.path}")
        token = self.get_token_from_headers(request)
        if not token:
            print("No Authorization token found.")
            request.user = AnonymousUser()
            return

        user = self.authenticate_token(token)
        print(user)
        if user:
            print(f"Authenticated User: {user}")
            request.user = user
        else:
            print("Token authentication failed")
            request.user = AnonymousUser()
        print(f"Request.user after middleware: {request.user}")
    
    def get_token_from_headers(self, request):
        auth_header = request.headers.get("Authorization")
        if auth_header and auth_header.startswith("Bearer "):
            return auth_header.split(" ")[1]
        return None
    
    
    def authenticate_token(self, token):
        try:
            response = requests.post(self.AUTH_SERVICE_URL, json={"token": token})
            print("Auth Service Response:", response)

            if response.status_code == 200:
                data = response.json()
                print("Response Data:", data)
                user_id = data.get("id")
                email = data.get("email")
                full_name = data.get("full_name")
                is_active = data.get("is_active")

                if user_id:
                    return SimpleUser(user_id=user_id, email=email, full_name=full_name, is_active=is_active)
        except requests.RequestException as e:
            print(f"Auth Service request failed: {e}")
        return None

this sends a request to the auth service to verify the token and returns the user data

but the issue now is when i want to send message to another user using this endpoint

api/chat/messages/{user_id}/ it throws an error

this is the views.py

class MessageView(APIView):
    permission_classes = [IsAuthenticatedCustom]
    authentication_classes = [JWTAuthentication]

    def get_queryset(self, user_id):
        print(f"Request user: {self.request.user}")
        return Message.objects.filter(
            sender_id=self.request.user.id, receiver_id=user_id
        ) | Message.objects.filter(
            sender_id=user_id, receiver_id=self.request.user.id
        )

    def get(self, request, user_id):
        print(f"GET method called with user: {request.user}, ID: {request.user.id}")
        print(f"Retrieving messages for user ID: {user_id}")
        messages = self.get_queryset(user_id=user_id)

        for message in messages:
            if message.receiver_id == request.user.id:
                message.is_read = True
                message.save(update_fields=['is_read'])

        serializer = MessageSerializer(messages, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)
    
    def post(self, request, user_id):
        print(f"Request user: {request.user}")  # Check user info
        data = {
            "message": request.data.get("message"),
            "receiver_id": user_id,
            "sender_id": request.user.id,
        }

        serializer = MessageSerializer(data=data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


it does not even print out the debug statement in the views

it just throws this
{
“detail”: “User not found”,
“code”: “user_not_found”
}

but the middeware returns the user info

New contributor

Chimaroke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật