【问题标题】:Serverless Django using Azure Functions使用 Azure Functions 的无服务器 Django
【发布时间】:2020-02-19 19:14:39
【问题描述】:

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

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

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

我想确定,即使有人对运行 Django 无服务器有一个可行的想法,并且对一个好的资源有一些指导?

【问题讨论】:

    标签: python django azure serverless-framework serverless


    【解决方案1】:

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

    首先,我按照以下步骤在自定义 docker Linux 容器中创建函数应用: https://docs.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 "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')
    

    重要的是

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

    在函数代码中设置 Django。

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

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 2020-09-09
      • 2018-11-18
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 2018-05-04
      相关资源
      最近更新 更多