Skip to content

Commit 7c53d7c

Browse files
authored
Add Google Cloud Functions Python runtime samples (GoogleCloudPlatform#1583)
1 parent f83bb36 commit 7c53d7c

19 files changed

+967
-0
lines changed

functions/README.rst

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
.. This file is automatically generated. Do not edit this file directly.
2+
3+
Google Cloud Functions Python Samples
4+
===============================================================================
5+
6+
.. image:: https://gstatic.com/cloudssh/images/open-btn.png
7+
:target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=/README.rst
8+
9+
10+
This directory contains samples for Google Cloud Functions. `Cloud Functions`_ is a lightweight, event-based, asynchronous compute solution that allows you to create small, single-purpose functions that respond to Cloud events without the need to manage a server or a runtime environment.
11+
12+
13+
14+
15+
.. _Cloud Functions: https://cloud.google.com/functions/docs/
16+
17+
Setup
18+
-------------------------------------------------------------------------------
19+
20+
21+
Authentication
22+
++++++++++++++
23+
24+
This sample requires you to have authentication setup. Refer to the
25+
`Authentication Getting Started Guide`_ for instructions on setting up
26+
credentials for applications.
27+
28+
.. _Authentication Getting Started Guide:
29+
https://cloud.google.com/docs/authentication/getting-started
30+
31+
Install Dependencies
32+
++++++++++++++++++++
33+
34+
#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions.
35+
36+
.. _Python Development Environment Setup Guide:
37+
https://cloud.google.com/python/setup
38+
39+
#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.
40+
41+
.. code-block:: bash
42+
43+
$ virtualenv env
44+
$ source env/bin/activate
45+
46+
#. Install the dependencies needed to run the samples.
47+
48+
.. code-block:: bash
49+
50+
$ pip install -r requirements.txt
51+
52+
.. _pip: https://pip.pypa.io/
53+
.. _virtualenv: https://virtualenv.pypa.io/
54+
55+
Samples
56+
-------------------------------------------------------------------------------
57+
58+
- `Hello World`_
59+
- Concepts_
60+
- `Logging & Monitoring`_
61+
- Tips_
62+
63+
64+
.. _Hello World: helloworld/
65+
.. _Concepts: concepts/
66+
.. _Logging & Monitoring: log/
67+
.. _Tips: tips/
68+
69+
The client library
70+
-------------------------------------------------------------------------------
71+
72+
This sample uses the `Google Cloud Client Library for Python`_.
73+
You can read the documentation for more details on API usage and use GitHub
74+
to `browse the source`_ and `report issues`_.
75+
76+
.. _Google Cloud Client Library for Python:
77+
https://googlecloudplatform.github.io/google-cloud-python/
78+
.. _browse the source:
79+
https://github.com/GoogleCloudPlatform/google-cloud-python
80+
.. _report issues:
81+
https://github.com/GoogleCloudPlatform/google-cloud-python/issues
82+
83+
84+
.. _Google Cloud SDK: https://cloud.google.com/sdk/

functions/README.rst.in

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# This file is used to generate README.rst
2+
3+
product:
4+
name: Google Cloud Functions
5+
short_name: GCF
6+
url: https://cloud.google.com/functions/docs/
7+
description: >
8+
Cloud Functions is a lightweight, event-based, asynchronous compute solution that allows you to create small, single-purpose functions that respond to Cloud events without the need to manage a server or a runtime environment.
9+
10+
setup:
11+
- auth
12+
- install_deps
13+
14+
samples:
15+
- name: Hello World
16+
file: helloworld/main.py
17+
18+
cloud_client_library: true

functions/concepts/README.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>
2+
3+
# Google Cloud Functions - Concepts sample
4+
5+
See:
6+
7+
* [Cloud Functions Concepts tutorial][tutorial]
8+
* [Cloud Functions Concepts sample source code][code]
9+
10+
[tutorial]: https://cloud.google.com/functions/docs/concepts/exec
11+
[code]: main.py

functions/concepts/main.py

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# Copyright 2018 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the 'License');
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an 'AS IS' BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import time
16+
17+
18+
# [START functions_concepts_stateless]
19+
# Global variable, modified within the function by using the global keyword.
20+
count = 0
21+
22+
23+
def statelessness(request):
24+
"""
25+
HTTP Cloud Function that counts how many times it is executed
26+
within a specific instance.
27+
Args:
28+
request (flask.Request): The request object.
29+
Returns:
30+
The response text, or any set of values that can be turned into a
31+
Response object using `make_response`
32+
<http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>.
33+
"""
34+
global count
35+
count += 1
36+
37+
# Note: the total function invocation count across
38+
# all instances may not be equal to this value!
39+
return 'Instance execution count: {}'.format(count)
40+
# [END functions_concepts_stateless]
41+
42+
43+
def heavy_computation():
44+
return time.time()
45+
46+
47+
def light_computation():
48+
return time.time()
49+
50+
51+
# [START functions_tips_scopes]
52+
# Global (instance-wide) scope
53+
# This computation runs at instance cold-start
54+
instance_var = heavy_computation()
55+
56+
57+
def scope_demo(request):
58+
"""
59+
HTTP Cloud Function that declares a variable.
60+
Args:
61+
request (flask.Request): The request object.
62+
Returns:
63+
The response text, or any set of values that can be turned into a
64+
Response object using `make_response`
65+
<http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>.
66+
"""
67+
68+
# Per-function scope
69+
# This computation runs every time this function is called
70+
function_var = light_computation()
71+
return 'Instance: {}; function: {}'.format(instance_var, function_var)
72+
# [END functions_tips_scopes]
73+
74+
75+
# [START functions_concepts_requests]
76+
def make_request(request):
77+
"""
78+
HTTP Cloud Function that makes another HTTP request.
79+
Args:
80+
request (flask.Request): The request object.
81+
Returns:
82+
The response text, or any set of values that can be turned into a
83+
Response object using `make_response`
84+
<http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>.
85+
"""
86+
import requests
87+
88+
# The URL to send the request to
89+
url = 'http://example.com'
90+
91+
# Process the request
92+
response = requests.get(url)
93+
response.raise_for_status()
94+
return 'Success!'
95+
# [END functions_concepts_requests]
96+
97+
98+
# [START functions_concepts_after_timeout]
99+
def timeout(request):
100+
print('Function running...')
101+
time.sleep(120)
102+
103+
# May not execute if function's timeout is <2 minutes
104+
return 'Done!'
105+
# [END functions_concepts_after_timeout]
106+
107+
108+
# [START functions_concepts_filesystem]
109+
def list_files(request):
110+
import os
111+
from os import path
112+
113+
root = path.dirname(path.abspath(__file__))
114+
children = os.listdir(root)
115+
files = [c for c in children if path.isfile(path.join(root, c))]
116+
return 'Files: {}'.format(files)
117+
# [END functions_concepts_filesystem]

functions/concepts/main_test.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Copyright 2018 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the 'License');
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an 'AS IS' BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
import flask
17+
import pytest
18+
import requests
19+
import responses
20+
21+
import main
22+
23+
24+
# Create a fake "app" for generating test request contexts.
25+
@pytest.fixture(scope="module")
26+
def app():
27+
return flask.Flask(__name__)
28+
29+
30+
def test_statelessness(app):
31+
with app.test_request_context():
32+
res = main.statelessness(flask.request)
33+
assert res == 'Instance execution count: 1'
34+
res = main.statelessness(flask.request)
35+
assert res == 'Instance execution count: 2'
36+
37+
38+
def test_scope_demo(app):
39+
with app.test_request_context():
40+
main.scope_demo(flask.request)
41+
42+
43+
@responses.activate
44+
def test_make_request_200(app):
45+
responses.add(responses.GET, 'http://example.com',
46+
json={'status': 'OK'}, status=200)
47+
with app.test_request_context():
48+
main.make_request(flask.request)
49+
50+
51+
@responses.activate
52+
def test_make_request_404(app):
53+
responses.add(responses.GET, 'http://example.com',
54+
json={'error': 'not found'}, status=404)
55+
with app.test_request_context():
56+
with pytest.raises(requests.exceptions.HTTPError):
57+
main.make_request(flask.request)
58+
59+
60+
def test_list_files(app):
61+
with app.test_request_context():
62+
res = main.list_files(flask.request)
63+
assert 'main.py' in res

functions/helloworld/README.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>
2+
3+
# Google Cloud Functions - Hello World sample
4+
5+
See:
6+
7+
* [Cloud Functions Hello World tutorial][tutorial]
8+
* [Cloud Functions Hello World sample source code][code]
9+
10+
[tutorial]: https://cloud.google.com/functions/docs/quickstart
11+
[code]: main.py

0 commit comments

Comments
 (0)