DEV Community

Dustin Ingram for Google Cloud

Posted on • Updated on

Serverless Python Quickstart with Google Cloud Functions

There's a new runtime in town: the Google Cloud team has brought everything awesome about Python to Google Cloud Functions by releasing a Python 3.7 runtime in addition to the existing Node.js runtime.

Cloud Functions are great for writing lightweight, self-contained microapps that can be individually scaled (and are a fraction of the cost of deploying a full webapp). They can also be used as "triggers": for example, automatically resizing an image into a smaller thumbnail once it's uploaded to a Google Cloud Storage bucket.

And now that you can write Cloud Functions in Python, you have the full power of the Python language (and any package from PyPI) at your disposal.

Initial setup

Cloud Functions have a simple directory structure:

.
├── main.py
└── requirements.txt
Enter fullscreen mode Exit fullscreen mode

In main.py, we'll define our function. In requirements.txt, we'll add any requirements that we might need to install from PyPI (or just leave it empty if there aren't any).

Writing our function

To start, let's write a simple function in our main.py file that just says hello:

def hello(request):
    return "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Running locally

To quickly test out our function, we can run it locally before deploying.

You'll need Python installed to follow this part. If you don't yet, see "Setting Up A Python Development Environment".

Once you've got a Python environment locally, we can add the following code to the end of our main.py file:

if __name__ == '__main__':
    from flask import Flask, request
    app = Flask(__name__)
    app.route('/')(lambda: hello(request))
    app.run()
Enter fullscreen mode Exit fullscreen mode

Next, create a virtual environment, activate it, and install Flask:

$ python -m venv env
$ source env/bin/activate
(env) $ pip install flask
Collecting flask
  ...
Successfully installed Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-6.7
flask-1.0.2 itsdangerous-0.24
Enter fullscreen mode Exit fullscreen mode

Run it as follows:

$ python main.py
Enter fullscreen mode Exit fullscreen mode

...and visit http://localhost:5000 to see your endpoint locally.

Deploying our function

Our function is only useful if it's deployed! Before deploying our function, you'll need to install and initialize the gcloud command line tool.

Once the gcloud SDK is installed, we can deploy our function with one line:

$ gcloud beta functions deploy hello --trigger-http --runtime python37 --project YOUR_PROJECT_NAME
Enter fullscreen mode Exit fullscreen mode

Once deployed, this command will give you a link to your live function.

Passing in variables

You're probably going to want to pass some data into your function. One way to do this is via URL parameters, like http://foo.bar/hello?name=Dustin. Let's make our example optionally take a parameter called name and use that instead of "World":

def hello(request):
    name = request.args.get('name', 'World')
    return f"Hello {name}!"
Enter fullscreen mode Exit fullscreen mode

Then when we redeploying our function, and visit https://YOUR_PROJECT_NAME.cloudfunctions.net/hello?name=dev.to, it will say:

Hello dev.to!

Adding dependencies

One of the nice things about Cloud Functions is that you can install the same dependencies from PyPI that you would normally use anywhere else.

Let's add a dependency on the emoji package, so we can add an optional emoji to the end of our message as well.

We'll add the name and version of the package to our requirements.txt file:

emoji==0.5.1
Enter fullscreen mode Exit fullscreen mode

This will automatically get installed when we redeploy the function.

Next, we'll want to import and use the library in our function:

import emoji

def hello(request):
    name = request.args.get('name', 'World')
    reaction = emoji.emojize(request.args.get('reaction', '!'))
    return f"Hello {name} {reaction}"
Enter fullscreen mode Exit fullscreen mode

Then we can visit https://YOUR_PROJECT_NAME.cloudfunctions.net/hello?name=dev.to&reaction=:wave: and it will say:

Hello dev.to 👋

Next steps

There's lots more you can do with Cloud Functions! Follow the links below to learn how to:

All code © Google w/ Apache 2 license

Top comments (0)