python-2.7 - 通过 GKE POD 内的 Cron 执行时,无法使用 Python SDK 将消息发布到 GCP Pub/Sub

标签 python-2.7 cron google-cloud-platform google-cloud-pubsub google-kubernetes-engine

使用 PYthon SDK 将消息发布到 GCP Pub/SUb。代码在 GKE 上的 Kubernetes POD 内运行。

import pymysql
import os
import argparse
import time
from google.cloud import pubsub_v1

entries = ['jelly']

def publish_messages(project, topic_name):

  publisher = pubsub_v1.PublisherClient()
  topic_path = publisher.topic_path(project, topic_name)

  for n in entries:
    data = u'Message number {}'.format(n)
    data = data.encode('utf-8')
    publisher.publish(topic_path, data=data)
    print "Message %s sent to queue" % n

手动执行时脚本工作正常。但是,通过 Crontab 触发时会失败。

Error: No handlers could be found for logger google.cloud.pubsub_v1.publisher._batch.thread"

最佳答案

找到了解决方案。 默认情况下,Crontab 不读取系统环境变量。上面的 Python 代码需要环境变量“GOOGLE_APPLICATION_CREDENTIALS”,它保存服务帐户 key (在本例中为 ConfigMap)。 为了实现这一点,所有环境变量必须打印到运行时容器的“/etc/environment”文件中。 像这样的事情:

FROM ubuntu:latest
ADD send.py Jelly/send.py
COPY jellycron /etc/cron.d/jellycron
RUN apt-get update && apt-get install -y cron vim mysql-server curl python python-pip 
    && pip install --upgrade pymysql google-api-python-client google-cloud google- 
    cloud-pubsub && touch /var/log/cron.log && chmod 0644 /etc/cron.d/jellycron && 
    crontab /etc/cron.d/jellycron
CMD printenv >> /etc/environment && cron && tail -f /var/log/cron.log

关于python-2.7 - 通过 GKE POD 内的 Cron 执行时,无法使用 Python SDK 将消息发布到 GCP Pub/Sub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52096840/

相关文章:

python - 如何在迭代时从 json 中删除项目?

php - 如何解决 Cron 作业运行错误

docker - 如何在使用 gcloud compute instance update-container 或强制其使用默认驱动程序时设置日志驱动程序 gcplogs?

java - Stackdriver Logback 附加程序停止应用程序

Python 二维数组求和枚举

python-2.7 - pyqt4正确连接QCheckbox状态

python - 难以理解 wxPython 中的 wx.Sizer

python - 使用 notify-send 的 python 脚本的 crontab

php - 调度php脚本

performance - 仅使用谷歌云作为数据库