DEV Community

Mohammad Moallemi
Mohammad Moallemi

Posted on • Originally published at mmoallemi99.com

Serverless Micro Django | Lightweight, yet powerful Python utility for lambda functions


https://github.com/mmoallemi99/serverless-micro-django/

A couple of weeks ago I had this task in agileful to refactor and improve some AWS lambda functions.

There was a bunch of pure SQL queries written alongside python codes which made me think, what if we could use standalone Django ORM in our python lambda functions?

So I did some digging on how we can use my beloved ORM in python scripts despite the serverless stuff, there were some vague and old answers but I managed to make something out of it.
It’s as simple as defining a database connection settings and calling django.setup().

Standalone Django ORM

Here is the minimal python code needed to use standalone Django ORM:


handler.py


serverless_micro_django/settings.py

Plus these two files you need to create your desired Django app models. (e.g. videos_app/models.py)

There is one downside in this way of using Django and that is the lack of manage.py!
I haven’t got time to try adding manage.py commands so I added some helper scripts like the ones below:


makemigrations.py / migrate.py

So even if you just need Django ORM without all the serverless and fancy stuff use the codes above and you’re good to go. Or check out the GitHub repository:
https://github.com/mmoallemi99/serverless-micro-django

Serverless Micro Django!

So let’s make it Serverless!
As we know lambda functions must accept two function parameters: event, context.

As SMD (Serverless Micro Django) is supposed to be lightweight and micro! it doesn’t support any REST API like Django & Flask. Just function!

Hence when you are invoking the function you must pass your desired action/event in lambda event argument:


test_lambda.py

And in the end, I developed a ModelController so I can execute the events. Which I’m not going to get into and talk about.

I’ve also done some event input validations and modeling using PyDantic which you can find in the project’s GitHub repository.

I know there is a long way for SMD to become mature and production-ready. I would gladly accept and be open to contributions and feedback. (Documenting, Development, Content Writing, etc…)

GitHub Repository:
https://github.com/mmoallemi99/serverless-micro-django

Originally published at https://mmoallemi99.com

Top comments (0)