gpt4 book ai didi

python - 使用 Azure Functions 的无服务器 Django

转载 作者:行者123 更新时间:2023-12-04 04:23:28 25 4
gpt4 key购买 nike

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

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

我一直在尝试几种方法,包括 Python on Azure: Part 4—Running serverless DjangoServerless Framework ,但我仍然无法让环境无错误地运行。

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

最佳答案

我不知道您到底想用 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=programming-language-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 "定时器触发器"

并启动 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')

重要的部分是

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

在函数代码中设置 Django。

Azure Function 文件夹(例如 my-function)位于项目的顶层。 IE。与包含命令的 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)

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

关于python - 使用 Azure Functions 的无服务器 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com