0

everyone!

I really need to get a content from a json file in the same folder as my main.py file. The problem is: Google Cloud Function can't run the open() statement. As the following error appears:

No such file or directory: 'mytest.json'

Now, I'm uploading my files in the Cloud Storage, but I wish it in the Cloud Source. So, how can I get my json file content from the Cloud Source?

This is my code structure in the 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'])
  • You should be able to read the files that you deployed with your function. Please edit the question to show the actual code that isn't working the way you expect. – Doug Stevenson Jan 30 '20 at 18:07
  • Do you have a typo? In your question you use the filename `mytest.json` but in the tree it shows `myjson.json`. – Dustin Ingram Jan 30 '20 at 18:17
  • Sorry Doug, I didn't think that, in this case, the code was important because it was really simple. I've just tried to read the json and the error rising in `open()` line. – Michel Guimarães Jan 30 '20 at 19:10

1 Answers1

1

I've tried to replicate your issue and was not able to get your error. As Doug has mentioned, when you deploy your function all the files in the directory are uploaded to the function's workspace. How are you deploying your function?

For this reproduction I used the Cloud Shell. In there I've created a directory named ReadJson with two files: main.py and myfile.json.

On the cloud shell, in the ReadJson directory I've executed this gcloud command:

gcloud functions deploy hello_world --runtime python37 --trigger-http

Using the code below, when triggering the function you should observe a "HelloWorld" on the browser.

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']
  • Thanks, @Oqueli. Actually, I realized that my json file was in a directory below my main file. So, in the `open()`, I was specifying the relative path instead of absolute path. I'm so sorry guys for my mistake to draw my stucture, but I thank for your help! – Michel Guimarães Jan 31 '20 at 15:53