Python Google云函数连接由p重置

2024-10-19 23:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如下所述:https://issuetracker.google.com/issues/113672049

交叉贴在这里:https://github.com/GoogleCloudPlatform/google-cloud-python/issues/5879

在使用Python中Google云函数的Firebase存储API时,我遇到了一个连接重置错误。在

部署的函数正在调用一个blob get,即

from firebase_admin import storage

def fn(request):
  bucket = 'my-firebase-bucket'
  path = '/thing'
  blob = storage.bucket(bucket).get_blob(path)

故障是间歇性的;该功能的成功率约为90%。在

它似乎更有可能在部署后第一次调用函数时失败。在


Tags: path函数httpsgithubcomgetbucket部署
2条回答

您可能需要检查您正在创建的客户机数量。在

Try to reuse network connections across function invocations, as described in Optimizing Networking. However, note that a connection that remains unused for 2 minutes might be closed by the system, and further attempts to use a closed connection will result in a "connection reset" error. Your code should either use a library that handles closed connections well, or handle them explicitly if using low-level networking constructs.

https://cloud.google.com/functions/docs/concepts/exec#network

请参阅此示例,其中他们只创建一次客户端并在函数中重用它:

import os
from google.cloud import pubsub_v1

# Create a global Pub/Sub client to avoid unneeded network activity
pubsub = pubsub_v1.PublisherClient()


def gcp_api_call(request):
    """
    HTTP Cloud Function that uses a cached client library instance to
    reduce the number of connections required per function invocation.
    Args:
        request (flask.Request): The request object.
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """

    project = os.getenv('GCP_PROJECT')
    request_json = request.get_json()

    topic_name = request_json['topic']
    topic_path = pubsub.topic_path(project, topic_name)

    # Process the request
    data = 'Test message'.encode('utf-8')
    pubsub.publish(topic_path, data=data)

    return '1 message published'

https://cloud.google.com/functions/docs/bestpractices/networking#accessing_google_apis

云函数是无状态的,但可以重用以前调用的全局状态。这在tipsthese docs中有解释。在

将全局状态与重试一起使用,应该会给您一个更健壮的函数:

from tenacity import retry, stop_after_attempt, wait_random
from firebase_admin import storage

@retry(stop=stop_after_attempt(3), wait=wait_random(min=1, max=2))
def get_bucket(storage):
    return storage.bucket('my-firebase-bucket')

@retry(stop=stop_after_attempt(3), wait=wait_random(min=1, max=2))
def get_blob(bucket, path):
    return bucket.get_blob(path)

bucket = get_bucket(storage)

def fn(request):
  path = '/thing'
  blob = get_blob(bucket, path)
  # etc..

相关问题 更多 >