'Serverless Django using Azure Functions

I have been trying to find ways to run Django on a Serverless environment on Azure Functions.

Assuming the constraint that I can only use Azure services, I want to make sure that the Django code that we will write should be portable(can be deployed anywhere else).

I have been trying a couple of methods including Python on Azure: Part 4—Running serverless Django and the Serverless Framework, still, I am not able to get the environment running error-free.

I wanted to be sure that even if someone has a working idea on running Django serverless and some guidance towards a good resource?



Solution 1:[1]

I don't know what you exactly want to do with Django, but I implemented Azure Functions to run Django commands (i.e. https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/).

First I followed the steps to create a function app in a custom docker Linux container: https://docs.microsoft.com/de-de/azure/azure-functions/functions-create-function-linux-custom-image?tabs=bash%2Cportal&pivots=programming-language-python

This includes setting up the function app via the Azure functions CLI at the root of my Django project and a Docker container which is based on the docker image mcr.microsoft.com/azure-functions/python:2.0-python3.7-slim

Then I created an Azure function via the CLI:

func new --name my-function --template "Timer trigger"

and to spin up Django and call the custom command my function code looks like

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function started at %s', utc_timestamp)
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mydjango.settings')
    django.setup()
    call_command('my_command')  # possible to add command params here
    logging.info('Successfully run my command')

The important part is

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mydjango.settings')
    django.setup()

to setup Django inside the function code.

The Azure Function folder (e.g. my-function) is on the top level of the project. I.e. the same level as the Django projects which contain the command e.g. project_1/management/commands/my_command.py

I.e. you have

root_project_folder
|_my_function (containing the Azure Function Python file and function.json) 
|_project_1/management/commands/my_command.py
|_django_setup (general Django folder)
|_AzureFunctionDockerfile (for Azure Functions)
|_host.json (for Azure Functions)
|_function.json (for Azure Functions)

Maybe it helps also for your purpose. If you have any questions I can also give you more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1