首页 > 解决方案 > 如何在 Google App Engine 上使用 Django 创建自定义 gunicorn 设置?

问题描述

Django项目结构

AppName
│   main.py
│   manage.yaml   
│   app.yaml  
│   gunicorn.conf.py  
│
└───AppName
│   │   wsgi.py
│   │   settings.py

应用程序.yaml


# [START django_app]
runtime: python37

handlers:
# This configures Google App Engine to serve the files in the app's static
# directory.
- url: /static
  static_dir: static/

# This handler routes all requests not caught above to your main app. It is
# required when static routes are defined, but can be omitted (along with
# the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto

entrypoint: gunicorn -c gunicorn.conf.py -b :8080 AppName.wsgi:app

# [END django_app]

gunicorn.conf.py

import multiprocessing

workers = multiprocessing.cpu_count() * 2 + 1

该应用程序在没有这条线的情况下工作。

entrypoint: gunicorn -c gunicorn.conf.py -b :8080 AppName.wsgi:app

但我需要有一个自定义 gunicorn.conf.py 才能动态设置工作人员的数量。

我一直在关注这个文档。https://cloud.google.com/appengine/docs/flexible/python/runtime

我已经尝试了这条线的许多变体,但我似乎无法让它工作。

还要设置保持应用程序运行的工作人员数量吗?我的目标是在出现任何尖峰时保持安全,并且即使应用程序有一段时间没有使用,也始终让工作人员启动。

谢谢。

标签: pythondjangogoogle-app-engine

解决方案


只要您遵循推荐的 app.yaml 入口点的文档,您的实际 gunicorn.conf.py 配置可能正在使用同步工作者。

我建议使用异步工作者,根据Gunicorn 文档,“可用的异步工作者基于 Greenlets(通过 Eventlet 和 Gevent)”,并且您现在拥有的同步工作者一次处理一个请求。

如此处所述,如果您的工作类需要额外的依赖项,例如 gevent 或 tornado,则需要在应用程序的requirements.txt.

还要确保在您的文件中添加了此处所述requirements.txt的指定版本gunicorn

尽管如此,正如你在这里提到的:

还要设置保持应用程序运行的工作人员数量吗?我的目标是在出现任何尖峰时保持安全,并且即使应用程序有一段时间没有使用,也始终让工作人员启动。

如果您真的想不惜一切代价保持应用程序运行,我强烈建议您使用GKE(Google Kubernetes Engine)。您不仅可以轻松选择工作人员的容量和能力,还可以使用运行应用程序的deployments多个副本。

如果您的某个应用程序崩溃或失败,您不必担心,因为 GKE 将难以实现您的“所需状态”,在这种情况下,“x”应用程序一直在运行。

我希望这有帮助。


推荐阅读