Structure your Python Module
  • 12 Mar 2024
  • 1 Minute to read
  • Dark
    Light
  • PDF

Structure your Python Module

  • Dark
    Light
  • PDF

Article summary

Your module's main directory example is a Django app generated with the startapp command.

In the example directory, you perform multiple functions.  For example, you can:

  • create a urls.py file to expose endpoints

  • create a viewsets.py file to leverage Django Rest Framework.

In the following scenario, we’re going to expose a /qrcode endpoint for our module that takes text and returns a base64 image.

  1. Create a viewsets.py file with the following contents.

    from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework import status, serializers
    import io
    import qrcode
    import base64
    
    class TextLikeSerializer(serializers.Serializer):
        text = serializers.CharField()
    
    class QRLikeSerializer(serializers.Serializer):
        qrcode = serializers.CharField()
    
    class QRCodeView(APIView):
        @extend_schema(request=TextLikeSerializer, responses=QRLikeSerializer)
        def post(self, request, *args, **kwargs):
            """
            This function takes text as input and returns Qrcode Image converted into base64 string.
            """
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_H,
                box_size=4,
                border=4,
            )
    
            qr.add_data(request.data["text"])
            qr.make(fit=True)
            img = qr.make_image()
    
            buffered = io.BytesIO()
            img.save(buffered, format="PNG")
            img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
            return Response({"qrcode": img_str}, status=status.HTTP_200_OK)
  2. Create a urls.py file that registers the endpoint in the router.

    from django.urls import path, include
    from rest_framework import routers
    
    from .viewsets import QRCodeView
    
    router = routers.DefaultRouter()
    urlpatterns = [
        path("", include(router.urls)),
        path("qrcode/", QRCodeView.as_view()),
    ]
  3. Install the module again.

    cb add django-example
    python manage.py runserver # restart if already running/
    
  4. Visit localhost:8000 and you should see this new endpoint.


Was this article helpful?

Changing your password will log you out immediately. Use the new password to log back in.
First name must have atleast 2 characters. Numbers and special characters are not allowed.
Last name must have atleast 1 characters. Numbers and special characters are not allowed.
Enter a valid email
Enter a valid password
Your profile has been successfully updated.