使用 Azure Functions 的无服务器 Django

ofn*_*ere 6 python django azure serverless-framework serverless

我一直在尝试寻找在 Azure Functions 上的无服务器环境中运行 Django 的方法。

\n\n

假设我只能使用 Azure 服务,我想确保我们将编写的 Django 代码应该是可移植的(可以部署在其他任何地方)。

\n\n

我一直在尝试几种方法,包括Azure 上的 Python:第 4 部分\xe2\x80\x94运行无服务器 Django无服务器框架,但我仍然无法使环境运行无错误。

\n\n

我想确定,即使有人有运行 Django 无服务器的工作想法以及一些关于良好资源的指导?

\n

lha*_*amp 6

我不知道您到底想用 Django 做什么,但我实现了 Azure Functions 来运行 Django 命令(即https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/)。

首先,我按照以下步骤在自定义 docker Linux 容器中创建函数应用程序: https: //learn.microsoft.com/de-de/azure/azure-functions/functions-create-function-linux-custom-image ?tabs =bash%2Cportal&pivots=编程语言-python

这包括通过位于 Django 项目根目录的 Azure 函数 CLI 和基于 docker 映像的 Docker 容器设置函数应用程序 mcr.microsoft.com/azure-functions/python:2.0-python3.7-slim

然后我通过 CLI 创建了一个 Azure 函数:

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

并启动 Django 并调用自定义命令,我的函数代码如下所示

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')
Run Code Online (Sandbox Code Playgroud)

重要的部分是

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mydjango.settings')
    django.setup()
Run Code Online (Sandbox Code Playgroud)

在函数代码中设置 Django。

Azure Function 文件夹(例如my-function)位于项目的顶层。即与包含命令的 Django 项目处于同一级别,例如project_1/management/commands/my_command.py

即你有

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)
Run Code Online (Sandbox Code Playgroud)

也许它也有助于您的目的。如果您有任何疑问,我也可以为您提供更多详细信息。