Local Testing for GCP Cloud Functions

It’s easy to write Google Cloud Functions in Python. The trick is to put a function that takes a single object in a file called main.py. Their example is simply:

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:
        return f'Hello World!'

But what they don’t help you with is how to run this locally. The answer is easy once you think about it, and a hint is in their example. They use Flask! Essentially GP runs Flask on the front of your function and sends the request object to it. No reason why you can’t do the same. Here is my very simple example:

from flask import Flask, request
import main

app = Flask(__name__)

@app.route('/', methods=['POST'])
def wrapper():
    return main.hello_world(request)

I saved this file called flasker.py and ran it via Flask as:

FLASK_APP=flasker.py flask run

It will tell you what URL to hit locally and it should do the same as when it’s running in GCP. If you have your GCP credentials setup correctly, your BigQuery and PubSub will work, etc. Note that it will work well, so make sure you are pointing to the correct environment. Also be careful that Flask doesn’t sneak into your dependencies. No telling what may happen then.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*