Skip to content

Instantly share code, notes, and snippets.

@ivanleoncz
Created September 1, 2020 01:54
Show Gist options
  • Save ivanleoncz/55c39ebbe0e8c7c9e70aab61ec2d04cf to your computer and use it in GitHub Desktop.
Save ivanleoncz/55c39ebbe0e8c7c9e70aab61ec2d04cf to your computer and use it in GitHub Desktop.
Mockup Python-baased Google Cloud Function
# On local environemnt: loaded via python-dotenv.
# On Cloug FUnction: defined on Environment Variables section and automatically loaded for the Cloud Function.
DEFAULT_MESSAGE="You haven't provided a message."
""" Cloud Function. """
import os
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:
default_message = os.getenv('DEFAULT_MESSAGE')
return f'{default_message}'
""" Designed for mockup purposes of Google Cloud Function from main.py. """
import sys
from flask import Flask, request
from dotenv import load_dotenv, find_dotenv
from main import hello_world
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def respond():
return hello_world(request)
if __name__ == "__main__":
"""
S ome cURL commands for simulation purposes:
curl http://127.0.0.1:5000/
curl http://127.0.0.1:5000/?message="wakeup%20now"
curl http://127.0.0.1:5000/ -X POST -H "Content-Type: application/json" -d '{"message":"wakeup"}'
"""
# Loading environment variables from .env
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
else:
print("[ERROR]: no .env file was found.")
sys.exit()
app.run()
click==7.1.2
Flask==1.1.2
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
python-dotenv==0.14.0
Werkzeug==1.0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment