forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
145 lines (111 loc) · 4.25 KB
/
Copy pathmain.py
File metadata and controls
145 lines (111 loc) · 4.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START functions_tips_infinite_retries]
from datetime import datetime
# The 'python-dateutil' package must be included in requirements.txt.
from dateutil import parser
# [END functions_tips_infinite_retries]
# [START functions_tips_connection_pooling]
import requests
# [END functions_tips_connection_pooling]
def file_wide_computation():
return sum(range(10))
def function_specific_computation():
return sum(range(10))
# [START functions_tips_lazy_globals]
# Always initialized (at cold-start)
non_lazy_global = file_wide_computation()
# Declared at cold-start, but only initialized if/when the function executes
lazy_global = None
def lazy_globals(request):
"""
HTTP Cloud Function that uses lazily-initialized globals.
Args:
request (flask.Request): The 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/0.12/api/#flask.Flask.make_response>.
"""
global lazy_global, non_lazy_global
# This value is initialized only if (and when) the function is called
if not lazy_global:
lazy_global = function_specific_computation()
return 'Lazy: {}, non-lazy: {}.'.format(lazy_global, non_lazy_global)
# [END functions_tips_lazy_globals]
# [START functions_tips_connection_pooling]
# Create a global HTTP session (which provides connection pooling)
session = requests.Session()
def connection_pooling(request):
"""
HTTP Cloud Function that uses a connection pool to make HTTP requests.
Args:
request (flask.Request): The 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/0.12/api/#flask.Flask.make_response>.
"""
# The URL to send the request to
url = 'http://example.com'
# Process the request
response = session.get(url)
response.raise_for_status()
return 'Success!'
# [END functions_tips_connection_pooling]
# [START functions_tips_infinite_retries]
def avoid_infinite_retries(data, context):
"""Background Cloud Function that only executes within a certain
time period after the triggering event.
Args:
data (dict): The event payload.
context (google.cloud.functions.Context): The event metadata.
Returns:
None; output is written to Stackdriver Logging
"""
timestamp = data.timestamp
event_time = parser.parse(timestamp)
event_age = (datetime.now() - event_time).total_seconds() * 1000
# Ignore events that are too old
if event_age > 10000:
print('Dropped {} (age {}ms)'.format(context.event_id, event_age))
return 'Timeout'
# Do what the function is supposed to do
print('Processed {} (age {}ms)'.format(context.event_id, event_age))
return
# [END functions_tips_infinite_retries]
# [START functions_tips_retry]
def retry_or_not(data, context):
"""Background Cloud Function that demonstrates how to toggle retries.
Args:
data (dict): The event payload.
context (google.cloud.functions.Context): The event metadata.
Returns:
None; output is written to Stackdriver Logging
"""
from google import cloud
error_client = cloud.error_reporting.Client()
if data.data.get('retry'):
try_again = True
else:
try_again = False
try:
raise Exception('I failed you')
except Exception as e:
error_client.report_exception()
if try_again:
raise e # Raise the exception and try again
else:
return # Swallow the exception and don't retry
# [END functions_tips_retry]