8000 feat: Add serverless scope sample by grant · Pull Request #2463 · GoogleCloudPlatform/python-docs-samples · GitHub
[go: up one dir, main page]

Skip to content

feat: Add serverless scope sample #2463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions functions/tips/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@

# [END functions_tips_connection_pooling]

from functools import reduce


# Placeholder
def file_wide_computation():
Expand All @@ -50,6 +52,42 @@ def function_specific_computation():
return 1


def light_computation():
numbers = list(range(1, 10))
return reduce(lambda x, t: t + x, numbers)


def heavy_computation():
# Multiplication is more computationally expensive than addition
numbers = list(range(1, 10))
return reduce(lambda x, t: t * x, numbers)


# [START functions_tips_global_scope]
# [START run_tips_global_scope]
# Global (instance-wide) scope
# This computation runs at instance cold-start
instance_var = heavy_computation()


def scope_demo(request):
"""
HTTP Cloud Function that declares a variable.
Args:
request (flask.Request): The request object.
<http://flask.pocoo.org/docs/1.0/api/#flask.Request>
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>.
"""
function_var = light_computation()
return 'Per instance: {}, per function: {}'.format(
instance_var, function_var)
# [END run_tips_global_scope]
# [END functions_tips_global_scope]


# [START functions_tips_lazy_globals]
# Always initialized (at cold-start)
non_lazy_global = file_wide_computation()
Expand Down
6 changes: 6 additions & 0 deletions functions/tips/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ def test_lazy_globals(app):
main.lazy_globals(flask.request)


def test_scope_demo(app):
with app.test_request_context():
res = main.scope_demo(flask.request)
assert res == 'Per instance: 362880, per function: 45'


@responses.activate
def test_connection_pooling_200(app):
responses.add(responses.GET, 'http://example.com',
Expand Down
0