pythongoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storagegoogle-cloud-source-repos

Is there a way to get a json file content in the Cloud Function?


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'])

Solution

  • 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']