gam7 7.20.3__py3-none-any.whl → 7.20.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of gam7 might be problematic. Click here for more details.

@@ -1,207 +0,0 @@
1
- # Copyright 2015 Google Inc. All rights reserved.
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
- """Helper functions for commonly used utilities."""
16
-
17
- import functools
18
- import inspect
19
- import logging
20
- import urllib
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
- POSITIONAL_WARNING = "WARNING"
25
- POSITIONAL_EXCEPTION = "EXCEPTION"
26
- POSITIONAL_IGNORE = "IGNORE"
27
- POSITIONAL_SET = frozenset(
28
- [POSITIONAL_WARNING, POSITIONAL_EXCEPTION, POSITIONAL_IGNORE]
29
- )
30
-
31
- positional_parameters_enforcement = POSITIONAL_WARNING
32
-
33
- _SYM_LINK_MESSAGE = "File: {0}: Is a symbolic link."
34
- _IS_DIR_MESSAGE = "{0}: Is a directory"
35
- _MISSING_FILE_MESSAGE = "Cannot access {0}: No such file or directory"
36
-
37
-
38
- def positional(max_positional_args):
39
- """A decorator to declare that only the first N arguments may be positional.
40
-
41
- This decorator makes it easy to support Python 3 style keyword-only
42
- parameters. For example, in Python 3 it is possible to write::
43
-
44
- def fn(pos1, *, kwonly1=None, kwonly2=None):
45
- ...
46
-
47
- All named parameters after ``*`` must be a keyword::
48
-
49
- fn(10, 'kw1', 'kw2') # Raises exception.
50
- fn(10, kwonly1='kw1') # Ok.
51
-
52
- Example
53
- ^^^^^^^
54
-
55
- To define a function like above, do::
56
-
57
- @positional(1)
58
- def fn(pos1, kwonly1=None, kwonly2=None):
59
- ...
60
-
61
- If no default value is provided to a keyword argument, it becomes a
62
- required keyword argument::
63
-
64
- @positional(0)
65
- def fn(required_kw):
66
- ...
67
-
68
- This must be called with the keyword parameter::
69
-
70
- fn() # Raises exception.
71
- fn(10) # Raises exception.
72
- fn(required_kw=10) # Ok.
73
-
74
- When defining instance or class methods always remember to account for
75
- ``self`` and ``cls``::
76
-
77
- class MyClass(object):
78
-
79
- @positional(2)
80
- def my_method(self, pos1, kwonly1=None):
81
- ...
82
-
83
- @classmethod
84
- @positional(2)
85
- def my_method(cls, pos1, kwonly1=None):
86
- ...
87
-
88
- The positional decorator behavior is controlled by
89
- ``_helpers.positional_parameters_enforcement``, which may be set to
90
- ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or
91
- ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do
92
- nothing, respectively, if a declaration is violated.
93
-
94
- Args:
95
- max_positional_arguments: Maximum number of positional arguments. All
96
- parameters after this index must be
97
- keyword only.
98
-
99
- Returns:
100
- A decorator that prevents using arguments after max_positional_args
101
- from being used as positional parameters.
102
-
103
- Raises:
104
- TypeError: if a keyword-only argument is provided as a positional
105
- parameter, but only if
106
- _helpers.positional_parameters_enforcement is set to
107
- POSITIONAL_EXCEPTION.
108
- """
109
-
110
- def positional_decorator(wrapped):
111
- @functools.wraps(wrapped)
112
- def positional_wrapper(*args, **kwargs):
113
- if len(args) > max_positional_args:
114
- plural_s = ""
115
- if max_positional_args != 1:
116
- plural_s = "s"
117
- message = (
118
- "{function}() takes at most {args_max} positional "
119
- "argument{plural} ({args_given} given)".format(
120
- function=wrapped.__name__,
121
- args_max=max_positional_args,
122
- args_given=len(args),
123
- plural=plural_s,
124
- )
125
- )
126
- if positional_parameters_enforcement == POSITIONAL_EXCEPTION:
127
- raise TypeError(message)
128
- elif positional_parameters_enforcement == POSITIONAL_WARNING:
129
- logger.warning(message)
130
- return wrapped(*args, **kwargs)
131
-
132
- return positional_wrapper
133
-
134
- if isinstance(max_positional_args, int):
135
- return positional_decorator
136
- else:
137
- args, _, _, defaults, _, _, _ = inspect.getfullargspec(max_positional_args)
138
- return positional(len(args) - len(defaults))(max_positional_args)
139
-
140
-
141
- def parse_unique_urlencoded(content):
142
- """Parses unique key-value parameters from urlencoded content.
143
-
144
- Args:
145
- content: string, URL-encoded key-value pairs.
146
-
147
- Returns:
148
- dict, The key-value pairs from ``content``.
149
-
150
- Raises:
151
- ValueError: if one of the keys is repeated.
152
- """
153
- urlencoded_params = urllib.parse.parse_qs(content)
154
- params = {}
155
- for key, value in urlencoded_params.items():
156
- if len(value) != 1:
157
- msg = "URL-encoded content contains a repeated value:" "%s -> %s" % (
158
- key,
159
- ", ".join(value),
160
- )
161
- raise ValueError(msg)
162
- params[key] = value[0]
163
- return params
164
-
165
-
166
- def update_query_params(uri, params):
167
- """Updates a URI with new query parameters.
168
-
169
- If a given key from ``params`` is repeated in the ``uri``, then
170
- the URI will be considered invalid and an error will occur.
171
-
172
- If the URI is valid, then each value from ``params`` will
173
- replace the corresponding value in the query parameters (if
174
- it exists).
175
-
176
- Args:
177
- uri: string, A valid URI, with potential existing query parameters.
178
- params: dict, A dictionary of query parameters.
179
-
180
- Returns:
181
- The same URI but with the new query parameters added.
182
- """
183
- parts = urllib.parse.urlparse(uri)
184
- query_params = parse_unique_urlencoded(parts.query)
185
- query_params.update(params)
186
- new_query = urllib.parse.urlencode(query_params)
187
- new_parts = parts._replace(query=new_query)
188
- return urllib.parse.urlunparse(new_parts)
189
-
190
-
191
- def _add_query_parameter(url, name, value):
192
- """Adds a query parameter to a url.
193
-
194
- Replaces the current value if it already exists in the URL.
195
-
196
- Args:
197
- url: string, url to add the query parameter to.
198
- name: string, query parameter name.
199
- value: string, query parameter value.
200
-
201
- Returns:
202
- Updated query parameter. Does not update the url if value is None.
203
- """
204
- if value is None:
205
- return url
206
- else:
207
- return update_query_params(url, {name: value})
@@ -1,315 +0,0 @@
1
- # Copyright 2014 Google Inc. All Rights Reserved.
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
- """Channel notifications support.
16
-
17
- Classes and functions to support channel subscriptions and notifications
18
- on those channels.
19
-
20
- Notes:
21
- - This code is based on experimental APIs and is subject to change.
22
- - Notification does not do deduplication of notification ids, that's up to
23
- the receiver.
24
- - Storing the Channel between calls is up to the caller.
25
-
26
-
27
- Example setting up a channel:
28
-
29
- # Create a new channel that gets notifications via webhook.
30
- channel = new_webhook_channel("https://example.com/my_web_hook")
31
-
32
- # Store the channel, keyed by 'channel.id'. Store it before calling the
33
- # watch method because notifications may start arriving before the watch
34
- # method returns.
35
- ...
36
-
37
- resp = service.objects().watchAll(
38
- bucket="some_bucket_id", body=channel.body()).execute()
39
- channel.update(resp)
40
-
41
- # Store the channel, keyed by 'channel.id'. Store it after being updated
42
- # since the resource_id value will now be correct, and that's needed to
43
- # stop a subscription.
44
- ...
45
-
46
-
47
- An example Webhook implementation using webapp2. Note that webapp2 puts
48
- headers in a case insensitive dictionary, as headers aren't guaranteed to
49
- always be upper case.
50
-
51
- id = self.request.headers[X_GOOG_CHANNEL_ID]
52
-
53
- # Retrieve the channel by id.
54
- channel = ...
55
-
56
- # Parse notification from the headers, including validating the id.
57
- n = notification_from_headers(channel, self.request.headers)
58
-
59
- # Do app specific stuff with the notification here.
60
- if n.resource_state == 'sync':
61
- # Code to handle sync state.
62
- elif n.resource_state == 'exists':
63
- # Code to handle the exists state.
64
- elif n.resource_state == 'not_exists':
65
- # Code to handle the not exists state.
66
-
67
-
68
- Example of unsubscribing.
69
-
70
- service.channels().stop(channel.body()).execute()
71
- """
72
- from __future__ import absolute_import
73
-
74
- import datetime
75
- import uuid
76
-
77
- from googleapiclient import _helpers as util
78
- from googleapiclient import errors
79
-
80
- # The unix time epoch starts at midnight 1970.
81
- EPOCH = datetime.datetime(1970, 1, 1)
82
-
83
- # Map the names of the parameters in the JSON channel description to
84
- # the parameter names we use in the Channel class.
85
- CHANNEL_PARAMS = {
86
- "address": "address",
87
- "id": "id",
88
- "expiration": "expiration",
89
- "params": "params",
90
- "resourceId": "resource_id",
91
- "resourceUri": "resource_uri",
92
- "type": "type",
93
- "token": "token",
94
- }
95
-
96
- X_GOOG_CHANNEL_ID = "X-GOOG-CHANNEL-ID"
97
- X_GOOG_MESSAGE_NUMBER = "X-GOOG-MESSAGE-NUMBER"
98
- X_GOOG_RESOURCE_STATE = "X-GOOG-RESOURCE-STATE"
99
- X_GOOG_RESOURCE_URI = "X-GOOG-RESOURCE-URI"
100
- X_GOOG_RESOURCE_ID = "X-GOOG-RESOURCE-ID"
101
-
102
-
103
- def _upper_header_keys(headers):
104
- new_headers = {}
105
- for k, v in headers.items():
106
- new_headers[k.upper()] = v
107
- return new_headers
108
-
109
-
110
- class Notification(object):
111
- """A Notification from a Channel.
112
-
113
- Notifications are not usually constructed directly, but are returned
114
- from functions like notification_from_headers().
115
-
116
- Attributes:
117
- message_number: int, The unique id number of this notification.
118
- state: str, The state of the resource being monitored.
119
- uri: str, The address of the resource being monitored.
120
- resource_id: str, The unique identifier of the version of the resource at
121
- this event.
122
- """
123
-
124
- @util.positional(5)
125
- def __init__(self, message_number, state, resource_uri, resource_id):
126
- """Notification constructor.
127
-
128
- Args:
129
- message_number: int, The unique id number of this notification.
130
- state: str, The state of the resource being monitored. Can be one
131
- of "exists", "not_exists", or "sync".
132
- resource_uri: str, The address of the resource being monitored.
133
- resource_id: str, The identifier of the watched resource.
134
- """
135
- self.message_number = message_number
136
- self.state = state
137
- self.resource_uri = resource_uri
138
- self.resource_id = resource_id
139
-
140
-
141
- class Channel(object):
142
- """A Channel for notifications.
143
-
144
- Usually not constructed directly, instead it is returned from helper
145
- functions like new_webhook_channel().
146
-
147
- Attributes:
148
- type: str, The type of delivery mechanism used by this channel. For
149
- example, 'web_hook'.
150
- id: str, A UUID for the channel.
151
- token: str, An arbitrary string associated with the channel that
152
- is delivered to the target address with each event delivered
153
- over this channel.
154
- address: str, The address of the receiving entity where events are
155
- delivered. Specific to the channel type.
156
- expiration: int, The time, in milliseconds from the epoch, when this
157
- channel will expire.
158
- params: dict, A dictionary of string to string, with additional parameters
159
- controlling delivery channel behavior.
160
- resource_id: str, An opaque id that identifies the resource that is
161
- being watched. Stable across different API versions.
162
- resource_uri: str, The canonicalized ID of the watched resource.
163
- """
164
-
165
- @util.positional(5)
166
- def __init__(
167
- self,
168
- type,
169
- id,
170
- token,
171
- address,
172
- expiration=None,
173
- params=None,
174
- resource_id="",
175
- resource_uri="",
176
- ):
177
- """Create a new Channel.
178
-
179
- In user code, this Channel constructor will not typically be called
180
- manually since there are functions for creating channels for each specific
181
- type with a more customized set of arguments to pass.
182
-
183
- Args:
184
- type: str, The type of delivery mechanism used by this channel. For
185
- example, 'web_hook'.
186
- id: str, A UUID for the channel.
187
- token: str, An arbitrary string associated with the channel that
188
- is delivered to the target address with each event delivered
189
- over this channel.
190
- address: str, The address of the receiving entity where events are
191
- delivered. Specific to the channel type.
192
- expiration: int, The time, in milliseconds from the epoch, when this
193
- channel will expire.
194
- params: dict, A dictionary of string to string, with additional parameters
195
- controlling delivery channel behavior.
196
- resource_id: str, An opaque id that identifies the resource that is
197
- being watched. Stable across different API versions.
198
- resource_uri: str, The canonicalized ID of the watched resource.
199
- """
200
- self.type = type
201
- self.id = id
202
- self.token = token
203
- self.address = address
204
- self.expiration = expiration
205
- self.params = params
206
- self.resource_id = resource_id
207
- self.resource_uri = resource_uri
208
-
209
- def body(self):
210
- """Build a body from the Channel.
211
-
212
- Constructs a dictionary that's appropriate for passing into watch()
213
- methods as the value of body argument.
214
-
215
- Returns:
216
- A dictionary representation of the channel.
217
- """
218
- result = {
219
- "id": self.id,
220
- "token": self.token,
221
- "type": self.type,
222
- "address": self.address,
223
- }
224
- if self.params:
225
- result["params"] = self.params
226
- if self.resource_id:
227
- result["resourceId"] = self.resource_id
228
- if self.resource_uri:
229
- result["resourceUri"] = self.resource_uri
230
- if self.expiration:
231
- result["expiration"] = self.expiration
232
-
233
- return result
234
-
235
- def update(self, resp):
236
- """Update a channel with information from the response of watch().
237
-
238
- When a request is sent to watch() a resource, the response returned
239
- from the watch() request is a dictionary with updated channel information,
240
- such as the resource_id, which is needed when stopping a subscription.
241
-
242
- Args:
243
- resp: dict, The response from a watch() method.
244
- """
245
- for json_name, param_name in CHANNEL_PARAMS.items():
246
- value = resp.get(json_name)
247
- if value is not None:
248
- setattr(self, param_name, value)
249
-
250
-
251
- def notification_from_headers(channel, headers):
252
- """Parse a notification from the webhook request headers, validate
253
- the notification, and return a Notification object.
254
-
255
- Args:
256
- channel: Channel, The channel that the notification is associated with.
257
- headers: dict, A dictionary like object that contains the request headers
258
- from the webhook HTTP request.
259
-
260
- Returns:
261
- A Notification object.
262
-
263
- Raises:
264
- errors.InvalidNotificationError if the notification is invalid.
265
- ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int.
266
- """
267
- headers = _upper_header_keys(headers)
268
- channel_id = headers[X_GOOG_CHANNEL_ID]
269
- if channel.id != channel_id:
270
- raise errors.InvalidNotificationError(
271
- "Channel id mismatch: %s != %s" % (channel.id, channel_id)
272
- )
273
- else:
274
- message_number = int(headers[X_GOOG_MESSAGE_NUMBER])
275
- state = headers[X_GOOG_RESOURCE_STATE]
276
- resource_uri = headers[X_GOOG_RESOURCE_URI]
277
- resource_id = headers[X_GOOG_RESOURCE_ID]
278
- return Notification(message_number, state, resource_uri, resource_id)
279
-
280
-
281
- @util.positional(2)
282
- def new_webhook_channel(url, token=None, expiration=None, params=None):
283
- """Create a new webhook Channel.
284
-
285
- Args:
286
- url: str, URL to post notifications to.
287
- token: str, An arbitrary string associated with the channel that
288
- is delivered to the target address with each notification delivered
289
- over this channel.
290
- expiration: datetime.datetime, A time in the future when the channel
291
- should expire. Can also be None if the subscription should use the
292
- default expiration. Note that different services may have different
293
- limits on how long a subscription lasts. Check the response from the
294
- watch() method to see the value the service has set for an expiration
295
- time.
296
- params: dict, Extra parameters to pass on channel creation. Currently
297
- not used for webhook channels.
298
- """
299
- expiration_ms = 0
300
- if expiration:
301
- delta = expiration - EPOCH
302
- expiration_ms = (
303
- delta.microseconds / 1000 + (delta.seconds + delta.days * 24 * 3600) * 1000
304
- )
305
- if expiration_ms < 0:
306
- expiration_ms = 0
307
-
308
- return Channel(
309
- "web_hook",
310
- str(uuid.uuid4()),
311
- token,
312
- url,
313
- expiration=expiration_ms,
314
- params=params,
315
- )