所有人!
我真的需要从与main.py文件相同的文件夹中的json文件获取内容。问题是:Google Cloud Function无法运行open()
语句。出现以下错误:
没有这样的文件或目录:'mytest。json'
现在,我将文件上传到Cloud Storage中,但希望将其上传到Cloud Source中。 所以,如何从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'])
我已尝试复制您的问题,但无法收到您的错误。如Doug所述,在部署功能时,目录中的所有文件都将上载到功能的工作区。您如何部署功能?
为了复制,我使用了Cloud Shell。在其中,我创建了一个名为ReadJson的目录,其中包含两个文件:main.py和myfile.json。
在云外壳上,在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']