python - 运行 Django 服务器时如何订阅 GCP Pub/Sub?

标签 python django google-cloud-platform google-cloud-pubsub

我有一个使用 django 的后端服务,我需要订阅一个托管在 GCP pub/sub 上的消息队列

这是 Google 提供的示例代码: https://cloud.google.com/pubsub/docs/pull

实现一个功能很容易,

但我必须通过如下命令启动 django 服务器:

python manage.py runserver

或者ASGI命令

这个订阅函数应该持续运行,最好在后台运行,

我怎样才能做到这一点?

我试过 django-crontab 或 django-background-task,但是这两个都需要手动运行命令,我认为这不是我需要的。

最佳答案

在Django中添加如下格式的新进程

taskApp/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            task_process.py

在startup.sh中添加如下命令

#!/bin/sh
gunicorn --bind :8000 --workers 3 --worker-class uvicorn.workers.UvicornWorker myapplication.asgi:application & python manage.py task_process

#!/bin/sh
    gunicorn --bind :8000 --workers 3 --worker-class uvicorn.workers.UvicornWorker myapplication.wsgi:application & python manage.py task_process

在 Dockerfile 中最后调用它

RUN chmod +x startup.sh
CMD ["./startup.sh"]

要检查处理是否正在运行,您可以如下验证

ps -ef | grep task_process

关于python - 运行 Django 服务器时如何订阅 GCP Pub/Sub?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66328787/

相关文章:

linux - Google Cloud Compute 上的多个 IP 地址

python - 我想停止 python 中的平方函数线程,但它不起作用?

python - 从列表中获取二元组

python - 比较两个相似的、不相同的 NLTK 树

python - 将表单传递到 HTML 页面 django

Django:发现强制转换为 Unicode NoneType

google-cloud-platform - Google Cloud 服务帐号监控警报

python - 如何在 for 循环中使用 vstack 以便将 csr_matrix 矩阵附加在一起

python - 类型错误 : Cannot create a consistent method resolution in django

google-cloud-platform - 上传 10gb 文件到 GCS