试图在谷歌云中查找已部署的 python 函数的当前项目 ID 会出错

use*_*505 4 python python-requests google-api-python-client google-cloud-python

我已经在谷歌云中部署了一个 python 3.7 函数。我需要通过代码获取 project-id 以找出它的部署位置。

我写了一个小的python 3.7脚本并通过google shell命令行对其进行测试

import urllib
import urllib.request
url="http://metadata.google.internal/computeMetadata/v1/project/project-id"
x=urllib.request.urlopen(url)
with x as response:
 x.read()
Run Code Online (Sandbox Code Playgroud)

不幸的是,这只是b''作为回应。虽然我已经使用了它,但我没有得到项目 ID

gcloud config set project my-project
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙,因为我是谷歌云和 python 的新手吗?谢谢。

这是下面的附加问题: 问题 2:

在我的本地系统中,我已经安装了 gcloud,如果我从那里运行上面的 python3.7 脚本

x=urllib.request.urlopen(url) #this line
Run Code Online (Sandbox Code Playgroud)

我从上面的行中收到此异常:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1350, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1240, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1286, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1235, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1006, in _send_output
    self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 946, in send
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 917, in connect
    self.sock = self._create_connection(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 787, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

The below changes as suggested by the answer also gives me empty string
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Dus*_*ram 5

在 Python 3.7 运行时,您可以通过环境变量获取项目 ID

import os
project_id = os.environ['GCP_PROJECT']
Run Code Online (Sandbox Code Playgroud)

在未来的运行时,此环境变量将不可用,您需要从元数据服务器获取项目 ID:

import urllib.request
url = "http://metadata.google.internal/computeMetadata/v1/project/project-id"
req = urllib.request.Request(url)
req.add_header("Metadata-Flavor", "Google")
project_id = urllib.request.urlopen(req).read().decode()
Run Code Online (Sandbox Code Playgroud)

在本地运行它会产生错误,因为您的本地机器无法解析http://metadata.google.internalURL——这仅适用于已部署的函数。