难以从 Flask 应用程序中访问 Google Text-to-Speech API

Difficulty accessing Google Text-to-Speech API from within Flask app

我在 Flask 应用程序中访问 Google 的文本转语音 Python API 时遇到困难。该应用程序 运行 安装在装有 Debian 10、Nginx/Gunicorn 和 Python 3.7 的容器中。在下面的代码中,客户端连接成功,但 synthesize_speech 请求无限期挂起(没有任何错误消息)。当我在没有 Flask 的同一容器中 运行 来自 Python 脚本的相同代码时,语音合成请求成功。但是,我可以毫无问题地从我的 Flask 应用程序调用其他外部 APIs,例如 AWS 的那些。

可能是什么原因造成的,或者我该如何诊断问题?我尝试切换到 texttospeech 库的 1.0.1 版,但没有成功。大概问题不是我的凭据,我相信我已经正确设置了凭据,否则连接请求将不会成功。

from google.cloud import texttospeech

# Connect (this is successful)
client = texttospeech.TextToSpeechClient()
input_text = texttospeech.SynthesisInput(text="God dag")
voice_parameters = texttospeech.VoiceSelectionParams(
    language_code="sv-SE",
    name="sv-SE-Wavenet-A"
)
audio_config = texttospeech.AudioConfig(
    audio_encoding=texttospeech.AudioEncoding.MP3
)

# Synthesize speech (this never completes)
response = client.synthesize_speech(
    request={
        "input": input_text,
        "voice": voice_parameters,
        "audio_config": audio_config
    }
)

点冻结

google-api-core==1.22.1
google-auth==1.20.1
google-cloud-texttospeech==2.2.0
googleapis-common-protos==1.52.0
grpcio==1.31.0
...

原来这个问题是由 gunicorn 的 gevent worker class 中的 monkey_patching 引起的。我已经通过将 gunicorn 中的 worker_class 更改为“同步”来解决问题,正如本页针对类似问题所建议的那样:

https://github.com/googleapis/google-cloud-python/issues/5848