DEV Community

Raphael Schubert
Raphael Schubert

Posted on

Using Masonite as microservice

We have a big project built on top of Django and now we started to break it on a few minor parts to be easy to maintain, update and scale.

So we decided to build some of the microservices with Masonite which is a good python framework and has almost all that we need built-in and ready to use.

So, how to integrate it, without need change much of our current logic?

We decided to basically consume it as a Rest API and built a small SDK that we override our code.

For sample:

class User(models.Model):
    # ...
    def get_user_documents(self):
        from documents.model import Document
        return Document.objects.filter(owner=self)

We know the above relation can be reached with related_name but as we had lots of implementations, it ends on some cases in a cyclic import, so on this sample case, we will use this approach.

So we moved all the documents of users to a new microservice because there we can scale the document server as we need and also improve it without the need to update the core server.

How we changed the class above?

class User(models.Model):
    # ...
    def get_user_documents(self):
        return DocumentsMS().get_user_documents(user_id=self.id)

And on our DocumentMS class, we have few classes that consume the REST API, for sample:

import requests
import json


class DocumentMS:
    def get_user_documents(user_id: int):
        url = "https://......"
        headers = {} # security token header
        querystring = {
            "user_id": user_id
        }

        response = requests.request("GET", url, headers=headers, params=querystring)
        return json.loads(response.text)

All of the codes we just wrote is for sample purposes and give you a simplistic way to use microservices along with your core server without the need to change your logic.

We normally use this for all implementations and then we dive deep as each situation needs.

I hope this gives you the north to how you can use microservices in an easy way.

On the next article I will show how we can create a small API to response the calls we just wrote.

Top comments (0)