【问题标题】:Intermediate Response before execution finish in python - Calling Cloud Function with other Cloud Function在 python 中执行完成之前的中间响应 - 使用其他云函数调用云函数
【发布时间】:2019-09-14 10:44:52
【问题描述】:

我有一个云函数在 python 中调用另一个云函数。我的问题是,当我调用下一个函数时,第一个函数等待其执行或超时。

关键是这是关于 Google Cloud Functions 的。特别是函数超时和最大 API 调用率之间的不匹配。我的问题是该函数的最大超时时间(540 秒)比我需要进行所需 API 调用的时间短,而且我不想创建更多触发器。

在调用第二个函数之后,我怎样才能让第一个(“调用者”)完成它的工作? 一些示例代码:

# main.py
# url: this-particular-cloud-function

# function initiated with a post request containing {"previous_tin_index": 0}
import requests
import time
import logging

final_tin_index = 100

def eat_spam(request):
  started_eating_spam = time.time()

  spam_json = request.get_json()
  spam_to_eat = spam_json["previous_tin_index"]

  for spam in range(spam_to_eat):
    time.sleep(5)
    previous_tin_index += 1
    logging.info("I hate spam....")
    finished_previous_spam_time = time.time() - started_eating_spam

  if finished_previous_spam_time >= 10:
    logging.info("Make it stop!")
    requests.post("this-particular-cloud-function", json={"previous_tin_index": previous_tin_index})

  return "200"

编辑:我知道固有的问题是函数永远不会达到返回值。我想知道这是否可以修复,例如,将代码重写为 Javascript 承诺。

附:我查看了Cloud Documentation,但在特定示例中似乎缺少python。

【问题讨论】:

    标签: python google-cloud-functions


    【解决方案1】:

    这可能会解决您的问题。

        def f1(x):
                print('f1', x)
                return f2, (x+1,)
        def f2(x):
                print('f2', x)
                return f1, (x+1,)
    
        f, args = f1, (0,)
        while True:
                f, args = f(*args)
    

    感谢post。

    尽管我认为您的问题在于工作流程。您正在返回一个值,但问题是您永远不会在代码中达到该点。假设您有 foo1() 并且在 foo1() 内部调用 foo2()。然后 foo()2 开始执行,但在您返回 foo1() 并继续直到您到达 return 命令之前, foo1() 已超时。

    如果您的问题没有得到解决,那么问题可能出在第二个函数上,因此可能需要查看此函数以解决您的问题。

    如果这有帮助,请告诉我。

    【讨论】:

    • 抱歉回复晚了,谢谢乔治!问题很清楚,但是我的用例需要执行多个函数。这是因为我正在调用一个配额有限的 API,这将超过我的函数超时。另外,我不想制作多个触发器。我只是想知道这在 Python 中是否很容易实现。有趣的想法,虽然返回一个函数!谢谢你的乔治
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2022-11-03
    • 2019-01-18
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多