Test Google Cloud Functions Locally (Local Development Server) - Python

Apr 20, 2019

There is a Node.js emulator, but no emulator for Python.

Google Cloud Functions for Python is actually using Flask, so you can simulate a local development server using Flask.

def test_message(request):    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!'if __name__ == '__main__':    from flask import Flask, request    app = Flask(__name__)    # option 1    @app.route('/', methods=['POST', 'GET'])    def test():        return test_message(request)    # option 2    app.add_url_rule('/test_message', 'test_message', test_message, methods=['POST', 'GET'], defaults={'request': request})    app.run(host='127.0.0.1', port=8088, debug=True)

Run the local development server.

python main.py

Test

http://127.0.0.1:8088/

or

http://127.0.0.1:8088/test_message

NOTE: If you local machine is running Python 2.7 and you need Python 3.7, refer to Install Latest Python (3.7) via Pyenv.

If you have dependencies of python libraries using requirement.txt

  • run pip install -r requirements.txt to install the relevant libraries
  • install Flask: pip install flask

NOYE: You might want to use virtualenvs. Pyenv support virtualenvs as well.

To support multiple cloud functions locally, you can use the following code.

functions = ['test_message', ...]# app.add_url_rule(f'/test_message', 'test_message', test_message, methods=['POST', 'GET'], defaults={'request': request})for function in functions:    app.add_url_rule(f'/{function}', function, locals()[function], methods=['POST', 'GET'], defaults={'request': request})

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.