<p>这里发生了两件事:</p>
<ol>
<li>您没有完全正确地使用<code>request-futures</code>。由于请求是异步发出的,因此需要在函数隐式返回之前阻止结果,否则它可能会在HTTP请求完成之前返回(尽管在本例中可能是这样):</li>
</ol>
<pre class="lang-py prettyprint-override"><code>session = FuturesSession()
future = session.get("{}".format(cf2_endpoint))
resp = future.result() # Block on the request completing
</code></pre>
<ol start=“2”>
<li>您对第二个函数发出的请求实际上不是经过身份验证的请求。默认情况下,云函数的出站请求不经过身份验证。如果您查看上面的实际响应,您将看到:</li>
</ol>
<pre><code>>>> resp.status_code
403
>>> resp.content
b'\n<html><head>\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<title>403 Forbidden</title>\n</head>\n<body text=#000000 bgcolor=#ffffff>\n<h1>Error: Forbidden</h1>\n<h2>Your client does not have permission to get URL <code>/function_two</code> from this server.</h2>\n<h2></h2>\n</body></html>\n'
</code></pre>
<p>您可以跳过许多障碍来正确验证此请求,如文档中所述:<a href="https://cloud.google.com/functions/docs/securing/authenticating#function-to-function" rel="nofollow noreferrer">https://cloud.google.com/functions/docs/securing/authenticating#function-to-function</a></p>
<p>但是,更好的替代方法是将第二个函数设置为“后台”函数,并通过从第一个函数发布的PubSub消息调用它:</p>
<pre class="lang-py prettyprint-override"><code>from google.cloud import pubsub
publisher = pubsub.PublisherClient()
topic_name = 'projects/{project_id}/topics/{topic}'.format(
project_id=<your project id>,
topic='MY_TOPIC_NAME', # Set this to something appropriate.
)
def function_one(request):
message = b'My first message!'
publisher.publish(topic_name, message)
def function_two(event, context):
message = event['data'].decode('utf-8')
print(message)
</code></pre>
<p>只要您的函数具有发布PubSub消息的权限,就不需要向HTTP请求添加授权,并且还可以确保至少一次传递</p>