【问题标题】:Is there a way to get a json file content in the Cloud Function?有没有办法在 Cloud Function 中获取 json 文件内容?
【发布时间】:2020-01-30 18:04:54
【问题描述】:

大家!

我确实需要从与我的 main.py 文件位于同一文件夹中的 json 文件中获取内容。问题是:Google Cloud Function 无法运行open() 语句。出现如下错误:

没有这样的文件或目录:'mytest.json'

现在,我正在将我的文件上传到 Cloud Storage,但我希望它在 Cloud Source 中。 那么,如何从云源获取我的 json 文件内容?

这是我在 Cloud Source 中的代码结构:

.
├── main.py
└── requirements.txt
└── mytest.json

mytest.json

{
    'test': 'Hello World!'
}

main.py:

import json
with open('mytest.json', 'r') as testJson:
     testDict = json.loads(testJson.read())
     print(testDict['test'])

【问题讨论】:

  • 您应该能够读取您使用函数部署的文件。请编辑问题以显示未按您期望的方式工作的实际代码。
  • 你有错字吗?在您的问题中,您使用文件名mytest.json,但在树中它显示myjson.json
  • 对不起,Doug,我不认为在这种情况下,代码很重要,因为它真的很简单。我刚刚尝试读取 json 和 open() 行中出现的错误。

标签: python google-cloud-platform google-cloud-functions google-cloud-storage google-cloud-source-repos


【解决方案1】:

我已尝试复制您的问题,但无法得到您的错误。正如 Doug 所提到的,当您部署函数时,目录中的所有文件都会上传到函数的工作区。你是如何部署你的功能的?

对于这个复制品,我使用了 Cloud Shell。在那里,我创建了一个名为 ReadJson 的目录,其中包含两个文件:main.py 和 myfile.json。

在云 shell 上,我在 ReadJson 目录中执行了这个 gcloud 命令:

gcloud 函数部署 hello_world --runtime python37 --trigger-http

使用下面的代码,当触发该函数时,您应该在浏览器上观察到一个“HelloWorld”。

def hello_world(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP 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>`.
"""
    request_json = request.get_json()
    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        with open('myfile.json') as json_file:
            data = json.load(json_file)
        return data['test']

【讨论】:

  • 谢谢,@Oqueli。实际上,我意识到我的 json 文件位于我的主文件下方的目录中。所以,在open() 中,我指定的是相对路径而不是绝对路径。对于我画出我的结构的错误,我很抱歉,但我感谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2010-09-12
  • 2017-08-05
  • 2011-04-15
相关资源
最近更新 更多