Skip to content

Commit 40a1010

Browse files
authored
feat: Add serverless scope sample (GoogleCloudPlatform#2463)
* feat: Add serverless scope sample, 142060621 * style: linter issues * fix: lint nits * fix: correct test values for the functions scope demo * fix type of test * fix return * Update main.py
1 parent 223abde commit 40a1010

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

functions/tips/main.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939

4040
# [END functions_tips_connection_pooling]
4141

42+
from functools import reduce
43+
4244

4345
# Placeholder
4446
def file_wide_computation():
@@ -50,6 +52,42 @@ def function_specific_computation():
5052
return 1
5153

5254

55+
def light_computation():
56+
numbers = list(range(1, 10))
57+
return reduce(lambda x, t: t + x, numbers)
58+
59+
60+
def heavy_computation():
61+
# Multiplication is more computationally expensive than addition
62+
numbers = list(range(1, 10))
63+
return reduce(lambda x, t: t * x, numbers)
64+
65+
66+
# [START functions_tips_global_scope]
67+
# [START run_tips_global_scope]
68+
# Global (instance-wide) scope
69+
# This computation runs at instance cold-start
70+
instance_var = heavy_computation()
71+
72+
73+
def scope_demo(request):
74+
"""
75+
HTTP Cloud Function that declares a variable.
76+
Args:
77+
request (flask.Request): The request object.
78+
<http://flask.pocoo.org/docs/1.0/api/#flask.Request>
79+
Returns:
80+
The response text, or any set of values that can be turned into a
81+
Response object using `make_response`
82+
<http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
83+
"""
84+
function_var = light_computation()
85+
return 'Per instance: {}, per function: {}'.format(
86+
instance_var, function_var)
87+
# [END run_tips_global_scope]
88+
# [END functions_tips_global_scope]
89+
90+
5391
# [START functions_tips_lazy_globals]
5492
# Always initialized (at cold-start)
5593
non_lazy_global = file_wide_computation()

functions/tips/main_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ def test_lazy_globals(app):
3535
main.lazy_globals(flask.request)
3636

3737

38+
def test_scope_demo(app):
39+
with app.test_request_context():
40+
res = main.scope_demo(flask.request)
41+
assert res == 'Per instance: 362880, per function: 45'
42+
43+
3844
@responses.activate
3945
def test_connection_pooling_200(app):
4046
responses.add(responses.GET, 'http://example.com',

0 commit comments

Comments
 (0)