OLD | NEW |
(Empty) | |
| 1 # Copyright 2015 Google Inc. |
| 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 base64 |
| 18 import calendar |
| 19 import datetime |
| 20 |
| 21 import six |
| 22 from six.moves import urllib |
| 23 |
| 24 |
| 25 CLOCK_SKEW_SECS = 300 # 5 minutes in seconds |
| 26 CLOCK_SKEW = datetime.timedelta(seconds=CLOCK_SKEW_SECS) |
| 27 |
| 28 |
| 29 def copy_docstring(source_class): |
| 30 """Decorator that copies a method's docstring from another class. |
| 31 |
| 32 Args: |
| 33 source_class (type): The class that has the documented method. |
| 34 |
| 35 Returns: |
| 36 Callable: A decorator that will copy the docstring of the same |
| 37 named method in the source class to the decorated method. |
| 38 """ |
| 39 def decorator(method): |
| 40 """Decorator implementation. |
| 41 |
| 42 Args: |
| 43 method (Callable): The method to copy the docstring to. |
| 44 |
| 45 Returns: |
| 46 Callable: the same method passed in with an updated docstring. |
| 47 |
| 48 Raises: |
| 49 ValueError: if the method already has a docstring. |
| 50 """ |
| 51 if method.__doc__: |
| 52 raise ValueError('Method already has a docstring.') |
| 53 |
| 54 source_method = getattr(source_class, method.__name__) |
| 55 method.__doc__ = source_method.__doc__ |
| 56 |
| 57 return method |
| 58 return decorator |
| 59 |
| 60 |
| 61 def utcnow(): |
| 62 """Returns the current UTC datetime. |
| 63 |
| 64 Returns: |
| 65 datetime: The current time in UTC. |
| 66 """ |
| 67 return datetime.datetime.utcnow() |
| 68 |
| 69 |
| 70 def datetime_to_secs(value): |
| 71 """Convert a datetime object to the number of seconds since the UNIX epoch. |
| 72 |
| 73 Args: |
| 74 value (datetime): The datetime to convert. |
| 75 |
| 76 Returns: |
| 77 int: The number of seconds since the UNIX epoch. |
| 78 """ |
| 79 return calendar.timegm(value.utctimetuple()) |
| 80 |
| 81 |
| 82 def to_bytes(value, encoding='utf-8'): |
| 83 """Converts a string value to bytes, if necessary. |
| 84 |
| 85 Unfortunately, ``six.b`` is insufficient for this task since in |
| 86 Python 2 because it does not modify ``unicode`` objects. |
| 87 |
| 88 Args: |
| 89 value (Union[str, bytes]): The value to be converted. |
| 90 encoding (str): The encoding to use to convert unicode to bytes. |
| 91 Defaults to "utf-8". |
| 92 |
| 93 Returns: |
| 94 bytes: The original value converted to bytes (if unicode) or as |
| 95 passed in if it started out as bytes. |
| 96 |
| 97 Raises: |
| 98 ValueError: If the value could not be converted to bytes. |
| 99 """ |
| 100 result = (value.encode(encoding) |
| 101 if isinstance(value, six.text_type) else value) |
| 102 if isinstance(result, six.binary_type): |
| 103 return result |
| 104 else: |
| 105 raise ValueError('{0!r} could not be converted to bytes'.format(value)) |
| 106 |
| 107 |
| 108 def from_bytes(value): |
| 109 """Converts bytes to a string value, if necessary. |
| 110 |
| 111 Args: |
| 112 value (Union[str, bytes]): The value to be converted. |
| 113 |
| 114 Returns: |
| 115 str: The original value converted to unicode (if bytes) or as passed in |
| 116 if it started out as unicode. |
| 117 |
| 118 Raises: |
| 119 ValueError: If the value could not be converted to unicode. |
| 120 """ |
| 121 result = (value.decode('utf-8') |
| 122 if isinstance(value, six.binary_type) else value) |
| 123 if isinstance(result, six.text_type): |
| 124 return result |
| 125 else: |
| 126 raise ValueError( |
| 127 '{0!r} could not be converted to unicode'.format(value)) |
| 128 |
| 129 |
| 130 def update_query(url, params, remove=None): |
| 131 """Updates a URL's query parameters. |
| 132 |
| 133 Replaces any current values if they are already present in the URL. |
| 134 |
| 135 Args: |
| 136 url (str): The URL to update. |
| 137 params (Mapping[str, str]): A mapping of query parameter |
| 138 keys to values. |
| 139 remove (Sequence[str]): Parameters to remove from the query string. |
| 140 |
| 141 Returns: |
| 142 str: The URL with updated query parameters. |
| 143 |
| 144 Examples: |
| 145 |
| 146 >>> url = 'http://example.com?a=1' |
| 147 >>> update_query(url, {'a': '2'}) |
| 148 http://example.com?a=2 |
| 149 >>> update_query(url, {'b': '3'}) |
| 150 http://example.com?a=1&b=3 |
| 151 >> update_query(url, {'b': '3'}, remove=['a']) |
| 152 http://example.com?b=3 |
| 153 |
| 154 """ |
| 155 if remove is None: |
| 156 remove = [] |
| 157 |
| 158 # Split the URL into parts. |
| 159 parts = urllib.parse.urlparse(url) |
| 160 # Parse the query string. |
| 161 query_params = urllib.parse.parse_qs(parts.query) |
| 162 # Update the query parameters with the new parameters. |
| 163 query_params.update(params) |
| 164 # Remove any values specified in remove. |
| 165 query_params = { |
| 166 key: value for key, value |
| 167 in six.iteritems(query_params) |
| 168 if key not in remove} |
| 169 # Re-encoded the query string. |
| 170 new_query = urllib.parse.urlencode(query_params, doseq=True) |
| 171 # Unsplit the url. |
| 172 new_parts = parts._replace(query=new_query) |
| 173 return urllib.parse.urlunparse(new_parts) |
| 174 |
| 175 |
| 176 def scopes_to_string(scopes): |
| 177 """Converts scope value to a string suitable for sending to OAuth 2.0 |
| 178 authorization servers. |
| 179 |
| 180 Args: |
| 181 scopes (Sequence[str]): The sequence of scopes to convert. |
| 182 |
| 183 Returns: |
| 184 str: The scopes formatted as a single string. |
| 185 """ |
| 186 return ' '.join(scopes) |
| 187 |
| 188 |
| 189 def string_to_scopes(scopes): |
| 190 """Converts stringifed scopes value to a list. |
| 191 |
| 192 Args: |
| 193 scopes (Union[Sequence, str]): The string of space-separated scopes |
| 194 to convert. |
| 195 Returns: |
| 196 Sequence(str): The separated scopes. |
| 197 """ |
| 198 if not scopes: |
| 199 return [] |
| 200 |
| 201 return scopes.split(' ') |
| 202 |
| 203 |
| 204 def padded_urlsafe_b64decode(value): |
| 205 """Decodes base64 strings lacking padding characters. |
| 206 |
| 207 Google infrastructure tends to omit the base64 padding characters. |
| 208 |
| 209 Args: |
| 210 value (Union[str, bytes]): The encoded value. |
| 211 |
| 212 Returns: |
| 213 bytes: The decoded value |
| 214 """ |
| 215 b64string = to_bytes(value) |
| 216 padded = b64string + b'=' * (-len(b64string) % 4) |
| 217 return base64.urlsafe_b64decode(padded) |
OLD | NEW |