discovery.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. """Client for discovery based APIs.
  15. A client library for Google's discovery based APIs.
  16. """
  17. from __future__ import absolute_import
  18. __author__ = "jcgregorio@google.com (Joe Gregorio)"
  19. __all__ = ["build", "build_from_document", "fix_method_name", "key2param"]
  20. from collections import OrderedDict
  21. import collections.abc
  22. # Standard library imports
  23. import copy
  24. from email.generator import BytesGenerator
  25. from email.mime.multipart import MIMEMultipart
  26. from email.mime.nonmultipart import MIMENonMultipart
  27. import http.client as http_client
  28. import io
  29. import json
  30. import keyword
  31. import logging
  32. import mimetypes
  33. import os
  34. import re
  35. import urllib
  36. import google.api_core.client_options
  37. from google.auth.exceptions import MutualTLSChannelError
  38. from google.auth.transport import mtls
  39. from google.oauth2 import service_account
  40. # Third-party imports
  41. import httplib2
  42. import uritemplate
  43. try:
  44. import google_auth_httplib2
  45. except ImportError: # pragma: NO COVER
  46. google_auth_httplib2 = None
  47. # Local imports
  48. from googleapiclient import _auth, mimeparse
  49. from googleapiclient._helpers import _add_query_parameter, positional
  50. from googleapiclient.errors import (
  51. HttpError,
  52. InvalidJsonError,
  53. MediaUploadSizeError,
  54. UnacceptableMimeTypeError,
  55. UnknownApiNameOrVersion,
  56. UnknownFileType,
  57. )
  58. from googleapiclient.http import (
  59. BatchHttpRequest,
  60. HttpMock,
  61. HttpMockSequence,
  62. HttpRequest,
  63. MediaFileUpload,
  64. MediaUpload,
  65. build_http,
  66. )
  67. from googleapiclient.model import JsonModel, MediaModel, RawModel
  68. from googleapiclient.schema import Schemas
  69. # The client library requires a version of httplib2 that supports RETRIES.
  70. httplib2.RETRIES = 1
  71. logger = logging.getLogger(__name__)
  72. URITEMPLATE = re.compile("{[^}]*}")
  73. VARNAME = re.compile("[a-zA-Z0-9_-]+")
  74. DISCOVERY_URI = (
  75. "https://www.googleapis.com/discovery/v1/apis/" "{api}/{apiVersion}/rest"
  76. )
  77. V1_DISCOVERY_URI = DISCOVERY_URI
  78. V2_DISCOVERY_URI = (
  79. "https://{api}.googleapis.com/$discovery/rest?" "version={apiVersion}"
  80. )
  81. DEFAULT_METHOD_DOC = "A description of how to use this function"
  82. HTTP_PAYLOAD_METHODS = frozenset(["PUT", "POST", "PATCH"])
  83. _MEDIA_SIZE_BIT_SHIFTS = {"KB": 10, "MB": 20, "GB": 30, "TB": 40}
  84. BODY_PARAMETER_DEFAULT_VALUE = {"description": "The request body.", "type": "object"}
  85. MEDIA_BODY_PARAMETER_DEFAULT_VALUE = {
  86. "description": (
  87. "The filename of the media request body, or an instance "
  88. "of a MediaUpload object."
  89. ),
  90. "type": "string",
  91. "required": False,
  92. }
  93. MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE = {
  94. "description": (
  95. "The MIME type of the media request body, or an instance "
  96. "of a MediaUpload object."
  97. ),
  98. "type": "string",
  99. "required": False,
  100. }
  101. _PAGE_TOKEN_NAMES = ("pageToken", "nextPageToken")
  102. # Parameters controlling mTLS behavior. See https://google.aip.dev/auth/4114.
  103. GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE"
  104. GOOGLE_API_USE_MTLS_ENDPOINT = "GOOGLE_API_USE_MTLS_ENDPOINT"
  105. # Parameters accepted by the stack, but not visible via discovery.
  106. # TODO(dhermes): Remove 'userip' in 'v2'.
  107. STACK_QUERY_PARAMETERS = frozenset(["trace", "pp", "userip", "strict"])
  108. STACK_QUERY_PARAMETER_DEFAULT_VALUE = {"type": "string", "location": "query"}
  109. # Library-specific reserved words beyond Python keywords.
  110. RESERVED_WORDS = frozenset(["body"])
  111. # patch _write_lines to avoid munging '\r' into '\n'
  112. # ( https://bugs.python.org/issue18886 https://bugs.python.org/issue19003 )
  113. class _BytesGenerator(BytesGenerator):
  114. _write_lines = BytesGenerator.write
  115. def fix_method_name(name):
  116. """Fix method names to avoid '$' characters and reserved word conflicts.
  117. Args:
  118. name: string, method name.
  119. Returns:
  120. The name with '_' appended if the name is a reserved word and '$' and '-'
  121. replaced with '_'.
  122. """
  123. name = name.replace("$", "_").replace("-", "_")
  124. if keyword.iskeyword(name) or name in RESERVED_WORDS:
  125. return name + "_"
  126. else:
  127. return name
  128. def key2param(key):
  129. """Converts key names into parameter names.
  130. For example, converting "max-results" -> "max_results"
  131. Args:
  132. key: string, the method key name.
  133. Returns:
  134. A safe method name based on the key name.
  135. """
  136. result = []
  137. key = list(key)
  138. if not key[0].isalpha():
  139. result.append("x")
  140. for c in key:
  141. if c.isalnum():
  142. result.append(c)
  143. else:
  144. result.append("_")
  145. return "".join(result)
  146. @positional(2)
  147. def build(
  148. serviceName,
  149. version,
  150. http=None,
  151. discoveryServiceUrl=None,
  152. developerKey=None,
  153. model=None,
  154. requestBuilder=HttpRequest,
  155. credentials=None,
  156. cache_discovery=True,
  157. cache=None,
  158. client_options=None,
  159. adc_cert_path=None,
  160. adc_key_path=None,
  161. num_retries=1,
  162. static_discovery=None,
  163. always_use_jwt_access=False,
  164. ):
  165. """Construct a Resource for interacting with an API.
  166. Construct a Resource object for interacting with an API. The serviceName and
  167. version are the names from the Discovery service.
  168. Args:
  169. serviceName: string, name of the service.
  170. version: string, the version of the service.
  171. http: httplib2.Http, An instance of httplib2.Http or something that acts
  172. like it that HTTP requests will be made through.
  173. discoveryServiceUrl: string, a URI Template that points to the location of
  174. the discovery service. It should have two parameters {api} and
  175. {apiVersion} that when filled in produce an absolute URI to the discovery
  176. document for that service.
  177. developerKey: string, key obtained from
  178. https://code.google.com/apis/console.
  179. model: googleapiclient.Model, converts to and from the wire format.
  180. requestBuilder: googleapiclient.http.HttpRequest, encapsulator for an HTTP
  181. request.
  182. credentials: oauth2client.Credentials or
  183. google.auth.credentials.Credentials, credentials to be used for
  184. authentication.
  185. cache_discovery: Boolean, whether or not to cache the discovery doc.
  186. cache: googleapiclient.discovery_cache.base.CacheBase, an optional
  187. cache object for the discovery documents.
  188. client_options: Mapping object or google.api_core.client_options, client
  189. options to set user options on the client.
  190. (1) The API endpoint should be set through client_options. If API endpoint
  191. is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used
  192. to control which endpoint to use.
  193. (2) client_cert_source is not supported, client cert should be provided using
  194. client_encrypted_cert_source instead. In order to use the provided client
  195. cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be
  196. set to `true`.
  197. More details on the environment variables are here:
  198. https://google.aip.dev/auth/4114
  199. adc_cert_path: str, client certificate file path to save the application
  200. default client certificate for mTLS. This field is required if you want to
  201. use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE`
  202. environment variable must be set to `true` in order to use this field,
  203. otherwise this field doesn't nothing.
  204. More details on the environment variables are here:
  205. https://google.aip.dev/auth/4114
  206. adc_key_path: str, client encrypted private key file path to save the
  207. application default client encrypted private key for mTLS. This field is
  208. required if you want to use the default client certificate.
  209. `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to
  210. `true` in order to use this field, otherwise this field doesn't nothing.
  211. More details on the environment variables are here:
  212. https://google.aip.dev/auth/4114
  213. num_retries: Integer, number of times to retry discovery with
  214. randomized exponential backoff in case of intermittent/connection issues.
  215. static_discovery: Boolean, whether or not to use the static discovery docs
  216. included in the library. The default value for `static_discovery` depends
  217. on the value of `discoveryServiceUrl`. `static_discovery` will default to
  218. `True` when `discoveryServiceUrl` is also not provided, otherwise it will
  219. default to `False`.
  220. always_use_jwt_access: Boolean, whether always use self signed JWT for service
  221. account credentials. This only applies to
  222. google.oauth2.service_account.Credentials.
  223. Returns:
  224. A Resource object with methods for interacting with the service.
  225. Raises:
  226. google.auth.exceptions.MutualTLSChannelError: if there are any problems
  227. setting up mutual TLS channel.
  228. """
  229. params = {"api": serviceName, "apiVersion": version}
  230. # The default value for `static_discovery` depends on the value of
  231. # `discoveryServiceUrl`. `static_discovery` will default to `True` when
  232. # `discoveryServiceUrl` is also not provided, otherwise it will default to
  233. # `False`. This is added for backwards compatability with
  234. # google-api-python-client 1.x which does not support the `static_discovery`
  235. # parameter.
  236. if static_discovery is None:
  237. if discoveryServiceUrl is None:
  238. static_discovery = True
  239. else:
  240. static_discovery = False
  241. if http is None:
  242. discovery_http = build_http()
  243. else:
  244. discovery_http = http
  245. service = None
  246. for discovery_url in _discovery_service_uri_options(discoveryServiceUrl, version):
  247. requested_url = uritemplate.expand(discovery_url, params)
  248. try:
  249. content = _retrieve_discovery_doc(
  250. requested_url,
  251. discovery_http,
  252. cache_discovery,
  253. serviceName,
  254. version,
  255. cache,
  256. developerKey,
  257. num_retries=num_retries,
  258. static_discovery=static_discovery,
  259. )
  260. service = build_from_document(
  261. content,
  262. base=discovery_url,
  263. http=http,
  264. developerKey=developerKey,
  265. model=model,
  266. requestBuilder=requestBuilder,
  267. credentials=credentials,
  268. client_options=client_options,
  269. adc_cert_path=adc_cert_path,
  270. adc_key_path=adc_key_path,
  271. always_use_jwt_access=always_use_jwt_access,
  272. )
  273. break # exit if a service was created
  274. except HttpError as e:
  275. if e.resp.status == http_client.NOT_FOUND:
  276. continue
  277. else:
  278. raise e
  279. # If discovery_http was created by this function, we are done with it
  280. # and can safely close it
  281. if http is None:
  282. discovery_http.close()
  283. if service is None:
  284. raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version))
  285. else:
  286. return service
  287. def _discovery_service_uri_options(discoveryServiceUrl, version):
  288. """
  289. Returns Discovery URIs to be used for attempting to build the API Resource.
  290. Args:
  291. discoveryServiceUrl:
  292. string, the Original Discovery Service URL preferred by the customer.
  293. version:
  294. string, API Version requested
  295. Returns:
  296. A list of URIs to be tried for the Service Discovery, in order.
  297. """
  298. if discoveryServiceUrl is not None:
  299. return [discoveryServiceUrl]
  300. if version is None:
  301. # V1 Discovery won't work if the requested version is None
  302. logger.warning(
  303. "Discovery V1 does not support empty versions. Defaulting to V2..."
  304. )
  305. return [V2_DISCOVERY_URI]
  306. else:
  307. return [DISCOVERY_URI, V2_DISCOVERY_URI]
  308. def _retrieve_discovery_doc(
  309. url,
  310. http,
  311. cache_discovery,
  312. serviceName,
  313. version,
  314. cache=None,
  315. developerKey=None,
  316. num_retries=1,
  317. static_discovery=True,
  318. ):
  319. """Retrieves the discovery_doc from cache or the internet.
  320. Args:
  321. url: string, the URL of the discovery document.
  322. http: httplib2.Http, An instance of httplib2.Http or something that acts
  323. like it through which HTTP requests will be made.
  324. cache_discovery: Boolean, whether or not to cache the discovery doc.
  325. serviceName: string, name of the service.
  326. version: string, the version of the service.
  327. cache: googleapiclient.discovery_cache.base.Cache, an optional cache
  328. object for the discovery documents.
  329. developerKey: string, Key for controlling API usage, generated
  330. from the API Console.
  331. num_retries: Integer, number of times to retry discovery with
  332. randomized exponential backoff in case of intermittent/connection issues.
  333. static_discovery: Boolean, whether or not to use the static discovery docs
  334. included in the library.
  335. Returns:
  336. A unicode string representation of the discovery document.
  337. """
  338. from . import discovery_cache
  339. if cache_discovery:
  340. if cache is None:
  341. cache = discovery_cache.autodetect()
  342. if cache:
  343. content = cache.get(url)
  344. if content:
  345. return content
  346. # When `static_discovery=True`, use static discovery artifacts included
  347. # with the library
  348. if static_discovery:
  349. content = discovery_cache.get_static_doc(serviceName, version)
  350. if content:
  351. return content
  352. else:
  353. raise UnknownApiNameOrVersion(
  354. "name: %s version: %s" % (serviceName, version)
  355. )
  356. actual_url = url
  357. # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
  358. # variable that contains the network address of the client sending the
  359. # request. If it exists then add that to the request for the discovery
  360. # document to avoid exceeding the quota on discovery requests.
  361. if "REMOTE_ADDR" in os.environ:
  362. actual_url = _add_query_parameter(url, "userIp", os.environ["REMOTE_ADDR"])
  363. if developerKey:
  364. actual_url = _add_query_parameter(url, "key", developerKey)
  365. logger.debug("URL being requested: GET %s", actual_url)
  366. # Execute this request with retries build into HttpRequest
  367. # Note that it will already raise an error if we don't get a 2xx response
  368. req = HttpRequest(http, HttpRequest.null_postproc, actual_url)
  369. resp, content = req.execute(num_retries=num_retries)
  370. try:
  371. content = content.decode("utf-8")
  372. except AttributeError:
  373. pass
  374. try:
  375. service = json.loads(content)
  376. except ValueError as e:
  377. logger.error("Failed to parse as JSON: " + content)
  378. raise InvalidJsonError()
  379. if cache_discovery and cache:
  380. cache.set(url, content)
  381. return content
  382. @positional(1)
  383. def build_from_document(
  384. service,
  385. base=None,
  386. future=None,
  387. http=None,
  388. developerKey=None,
  389. model=None,
  390. requestBuilder=HttpRequest,
  391. credentials=None,
  392. client_options=None,
  393. adc_cert_path=None,
  394. adc_key_path=None,
  395. always_use_jwt_access=False,
  396. ):
  397. """Create a Resource for interacting with an API.
  398. Same as `build()`, but constructs the Resource object from a discovery
  399. document that is it given, as opposed to retrieving one over HTTP.
  400. Args:
  401. service: string or object, the JSON discovery document describing the API.
  402. The value passed in may either be the JSON string or the deserialized
  403. JSON.
  404. base: string, base URI for all HTTP requests, usually the discovery URI.
  405. This parameter is no longer used as rootUrl and servicePath are included
  406. within the discovery document. (deprecated)
  407. future: string, discovery document with future capabilities (deprecated).
  408. http: httplib2.Http, An instance of httplib2.Http or something that acts
  409. like it that HTTP requests will be made through.
  410. developerKey: string, Key for controlling API usage, generated
  411. from the API Console.
  412. model: Model class instance that serializes and de-serializes requests and
  413. responses.
  414. requestBuilder: Takes an http request and packages it up to be executed.
  415. credentials: oauth2client.Credentials or
  416. google.auth.credentials.Credentials, credentials to be used for
  417. authentication.
  418. client_options: Mapping object or google.api_core.client_options, client
  419. options to set user options on the client.
  420. (1) The API endpoint should be set through client_options. If API endpoint
  421. is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used
  422. to control which endpoint to use.
  423. (2) client_cert_source is not supported, client cert should be provided using
  424. client_encrypted_cert_source instead. In order to use the provided client
  425. cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be
  426. set to `true`.
  427. More details on the environment variables are here:
  428. https://google.aip.dev/auth/4114
  429. adc_cert_path: str, client certificate file path to save the application
  430. default client certificate for mTLS. This field is required if you want to
  431. use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE`
  432. environment variable must be set to `true` in order to use this field,
  433. otherwise this field doesn't nothing.
  434. More details on the environment variables are here:
  435. https://google.aip.dev/auth/4114
  436. adc_key_path: str, client encrypted private key file path to save the
  437. application default client encrypted private key for mTLS. This field is
  438. required if you want to use the default client certificate.
  439. `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to
  440. `true` in order to use this field, otherwise this field doesn't nothing.
  441. More details on the environment variables are here:
  442. https://google.aip.dev/auth/4114
  443. always_use_jwt_access: Boolean, whether always use self signed JWT for service
  444. account credentials. This only applies to
  445. google.oauth2.service_account.Credentials.
  446. Returns:
  447. A Resource object with methods for interacting with the service.
  448. Raises:
  449. google.auth.exceptions.MutualTLSChannelError: if there are any problems
  450. setting up mutual TLS channel.
  451. """
  452. if client_options is None:
  453. client_options = google.api_core.client_options.ClientOptions()
  454. if isinstance(client_options, collections.abc.Mapping):
  455. client_options = google.api_core.client_options.from_dict(client_options)
  456. if http is not None:
  457. # if http is passed, the user cannot provide credentials
  458. banned_options = [
  459. (credentials, "credentials"),
  460. (client_options.credentials_file, "client_options.credentials_file"),
  461. ]
  462. for option, name in banned_options:
  463. if option is not None:
  464. raise ValueError(
  465. "Arguments http and {} are mutually exclusive".format(name)
  466. )
  467. if isinstance(service, str):
  468. service = json.loads(service)
  469. elif isinstance(service, bytes):
  470. service = json.loads(service.decode("utf-8"))
  471. if "rootUrl" not in service and isinstance(http, (HttpMock, HttpMockSequence)):
  472. logger.error(
  473. "You are using HttpMock or HttpMockSequence without"
  474. + "having the service discovery doc in cache. Try calling "
  475. + "build() without mocking once first to populate the "
  476. + "cache."
  477. )
  478. raise InvalidJsonError()
  479. # If an API Endpoint is provided on client options, use that as the base URL
  480. base = urllib.parse.urljoin(service["rootUrl"], service["servicePath"])
  481. audience_for_self_signed_jwt = base
  482. if client_options.api_endpoint:
  483. base = client_options.api_endpoint
  484. schema = Schemas(service)
  485. # If the http client is not specified, then we must construct an http client
  486. # to make requests. If the service has scopes, then we also need to setup
  487. # authentication.
  488. if http is None:
  489. # Does the service require scopes?
  490. scopes = list(
  491. service.get("auth", {}).get("oauth2", {}).get("scopes", {}).keys()
  492. )
  493. # If so, then the we need to setup authentication if no developerKey is
  494. # specified.
  495. if scopes and not developerKey:
  496. # Make sure the user didn't pass multiple credentials
  497. if client_options.credentials_file and credentials:
  498. raise google.api_core.exceptions.DuplicateCredentialArgs(
  499. "client_options.credentials_file and credentials are mutually exclusive."
  500. )
  501. # Check for credentials file via client options
  502. if client_options.credentials_file:
  503. credentials = _auth.credentials_from_file(
  504. client_options.credentials_file,
  505. scopes=client_options.scopes,
  506. quota_project_id=client_options.quota_project_id,
  507. )
  508. # If the user didn't pass in credentials, attempt to acquire application
  509. # default credentials.
  510. if credentials is None:
  511. credentials = _auth.default_credentials(
  512. scopes=client_options.scopes,
  513. quota_project_id=client_options.quota_project_id,
  514. )
  515. # The credentials need to be scoped.
  516. # If the user provided scopes via client_options don't override them
  517. if not client_options.scopes:
  518. credentials = _auth.with_scopes(credentials, scopes)
  519. # For google-auth service account credentials, enable self signed JWT if
  520. # always_use_jwt_access is true.
  521. if (
  522. credentials
  523. and isinstance(credentials, service_account.Credentials)
  524. and always_use_jwt_access
  525. and hasattr(service_account.Credentials, "with_always_use_jwt_access")
  526. ):
  527. credentials = credentials.with_always_use_jwt_access(always_use_jwt_access)
  528. credentials._create_self_signed_jwt(audience_for_self_signed_jwt)
  529. # If credentials are provided, create an authorized http instance;
  530. # otherwise, skip authentication.
  531. if credentials:
  532. http = _auth.authorized_http(credentials)
  533. # If the service doesn't require scopes then there is no need for
  534. # authentication.
  535. else:
  536. http = build_http()
  537. # Obtain client cert and create mTLS http channel if cert exists.
  538. client_cert_to_use = None
  539. use_client_cert = os.getenv(GOOGLE_API_USE_CLIENT_CERTIFICATE, "false")
  540. if not use_client_cert in ("true", "false"):
  541. raise MutualTLSChannelError(
  542. "Unsupported GOOGLE_API_USE_CLIENT_CERTIFICATE value. Accepted values: true, false"
  543. )
  544. if client_options and client_options.client_cert_source:
  545. raise MutualTLSChannelError(
  546. "ClientOptions.client_cert_source is not supported, please use ClientOptions.client_encrypted_cert_source."
  547. )
  548. if use_client_cert == "true":
  549. if (
  550. client_options
  551. and hasattr(client_options, "client_encrypted_cert_source")
  552. and client_options.client_encrypted_cert_source
  553. ):
  554. client_cert_to_use = client_options.client_encrypted_cert_source
  555. elif (
  556. adc_cert_path and adc_key_path and mtls.has_default_client_cert_source()
  557. ):
  558. client_cert_to_use = mtls.default_client_encrypted_cert_source(
  559. adc_cert_path, adc_key_path
  560. )
  561. if client_cert_to_use:
  562. cert_path, key_path, passphrase = client_cert_to_use()
  563. # The http object we built could be google_auth_httplib2.AuthorizedHttp
  564. # or httplib2.Http. In the first case we need to extract the wrapped
  565. # httplib2.Http object from google_auth_httplib2.AuthorizedHttp.
  566. http_channel = (
  567. http.http
  568. if google_auth_httplib2
  569. and isinstance(http, google_auth_httplib2.AuthorizedHttp)
  570. else http
  571. )
  572. http_channel.add_certificate(key_path, cert_path, "", passphrase)
  573. # If user doesn't provide api endpoint via client options, decide which
  574. # api endpoint to use.
  575. if "mtlsRootUrl" in service and (
  576. not client_options or not client_options.api_endpoint
  577. ):
  578. mtls_endpoint = urllib.parse.urljoin(
  579. service["mtlsRootUrl"], service["servicePath"]
  580. )
  581. use_mtls_endpoint = os.getenv(GOOGLE_API_USE_MTLS_ENDPOINT, "auto")
  582. if not use_mtls_endpoint in ("never", "auto", "always"):
  583. raise MutualTLSChannelError(
  584. "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
  585. )
  586. # Switch to mTLS endpoint, if environment variable is "always", or
  587. # environment varibable is "auto" and client cert exists.
  588. if use_mtls_endpoint == "always" or (
  589. use_mtls_endpoint == "auto" and client_cert_to_use
  590. ):
  591. base = mtls_endpoint
  592. if model is None:
  593. features = service.get("features", [])
  594. model = JsonModel("dataWrapper" in features)
  595. return Resource(
  596. http=http,
  597. baseUrl=base,
  598. model=model,
  599. developerKey=developerKey,
  600. requestBuilder=requestBuilder,
  601. resourceDesc=service,
  602. rootDesc=service,
  603. schema=schema,
  604. )
  605. def _cast(value, schema_type):
  606. """Convert value to a string based on JSON Schema type.
  607. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
  608. JSON Schema.
  609. Args:
  610. value: any, the value to convert
  611. schema_type: string, the type that value should be interpreted as
  612. Returns:
  613. A string representation of 'value' based on the schema_type.
  614. """
  615. if schema_type == "string":
  616. if type(value) == type("") or type(value) == type(""):
  617. return value
  618. else:
  619. return str(value)
  620. elif schema_type == "integer":
  621. return str(int(value))
  622. elif schema_type == "number":
  623. return str(float(value))
  624. elif schema_type == "boolean":
  625. return str(bool(value)).lower()
  626. else:
  627. if type(value) == type("") or type(value) == type(""):
  628. return value
  629. else:
  630. return str(value)
  631. def _media_size_to_long(maxSize):
  632. """Convert a string media size, such as 10GB or 3TB into an integer.
  633. Args:
  634. maxSize: string, size as a string, such as 2MB or 7GB.
  635. Returns:
  636. The size as an integer value.
  637. """
  638. if len(maxSize) < 2:
  639. return 0
  640. units = maxSize[-2:].upper()
  641. bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units)
  642. if bit_shift is not None:
  643. return int(maxSize[:-2]) << bit_shift
  644. else:
  645. return int(maxSize)
  646. def _media_path_url_from_info(root_desc, path_url):
  647. """Creates an absolute media path URL.
  648. Constructed using the API root URI and service path from the discovery
  649. document and the relative path for the API method.
  650. Args:
  651. root_desc: Dictionary; the entire original deserialized discovery document.
  652. path_url: String; the relative URL for the API method. Relative to the API
  653. root, which is specified in the discovery document.
  654. Returns:
  655. String; the absolute URI for media upload for the API method.
  656. """
  657. return "%(root)supload/%(service_path)s%(path)s" % {
  658. "root": root_desc["rootUrl"],
  659. "service_path": root_desc["servicePath"],
  660. "path": path_url,
  661. }
  662. def _fix_up_parameters(method_desc, root_desc, http_method, schema):
  663. """Updates parameters of an API method with values specific to this library.
  664. Specifically, adds whatever global parameters are specified by the API to the
  665. parameters for the individual method. Also adds parameters which don't
  666. appear in the discovery document, but are available to all discovery based
  667. APIs (these are listed in STACK_QUERY_PARAMETERS).
  668. SIDE EFFECTS: This updates the parameters dictionary object in the method
  669. description.
  670. Args:
  671. method_desc: Dictionary with metadata describing an API method. Value comes
  672. from the dictionary of methods stored in the 'methods' key in the
  673. deserialized discovery document.
  674. root_desc: Dictionary; the entire original deserialized discovery document.
  675. http_method: String; the HTTP method used to call the API method described
  676. in method_desc.
  677. schema: Object, mapping of schema names to schema descriptions.
  678. Returns:
  679. The updated Dictionary stored in the 'parameters' key of the method
  680. description dictionary.
  681. """
  682. parameters = method_desc.setdefault("parameters", {})
  683. # Add in the parameters common to all methods.
  684. for name, description in root_desc.get("parameters", {}).items():
  685. parameters[name] = description
  686. # Add in undocumented query parameters.
  687. for name in STACK_QUERY_PARAMETERS:
  688. parameters[name] = STACK_QUERY_PARAMETER_DEFAULT_VALUE.copy()
  689. # Add 'body' (our own reserved word) to parameters if the method supports
  690. # a request payload.
  691. if http_method in HTTP_PAYLOAD_METHODS and "request" in method_desc:
  692. body = BODY_PARAMETER_DEFAULT_VALUE.copy()
  693. body.update(method_desc["request"])
  694. parameters["body"] = body
  695. return parameters
  696. def _fix_up_media_upload(method_desc, root_desc, path_url, parameters):
  697. """Adds 'media_body' and 'media_mime_type' parameters if supported by method.
  698. SIDE EFFECTS: If there is a 'mediaUpload' in the method description, adds
  699. 'media_upload' key to parameters.
  700. Args:
  701. method_desc: Dictionary with metadata describing an API method. Value comes
  702. from the dictionary of methods stored in the 'methods' key in the
  703. deserialized discovery document.
  704. root_desc: Dictionary; the entire original deserialized discovery document.
  705. path_url: String; the relative URL for the API method. Relative to the API
  706. root, which is specified in the discovery document.
  707. parameters: A dictionary describing method parameters for method described
  708. in method_desc.
  709. Returns:
  710. Triple (accept, max_size, media_path_url) where:
  711. - accept is a list of strings representing what content types are
  712. accepted for media upload. Defaults to empty list if not in the
  713. discovery document.
  714. - max_size is a long representing the max size in bytes allowed for a
  715. media upload. Defaults to 0L if not in the discovery document.
  716. - media_path_url is a String; the absolute URI for media upload for the
  717. API method. Constructed using the API root URI and service path from
  718. the discovery document and the relative path for the API method. If
  719. media upload is not supported, this is None.
  720. """
  721. media_upload = method_desc.get("mediaUpload", {})
  722. accept = media_upload.get("accept", [])
  723. max_size = _media_size_to_long(media_upload.get("maxSize", ""))
  724. media_path_url = None
  725. if media_upload:
  726. media_path_url = _media_path_url_from_info(root_desc, path_url)
  727. parameters["media_body"] = MEDIA_BODY_PARAMETER_DEFAULT_VALUE.copy()
  728. parameters["media_mime_type"] = MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE.copy()
  729. return accept, max_size, media_path_url
  730. def _fix_up_method_description(method_desc, root_desc, schema):
  731. """Updates a method description in a discovery document.
  732. SIDE EFFECTS: Changes the parameters dictionary in the method description with
  733. extra parameters which are used locally.
  734. Args:
  735. method_desc: Dictionary with metadata describing an API method. Value comes
  736. from the dictionary of methods stored in the 'methods' key in the
  737. deserialized discovery document.
  738. root_desc: Dictionary; the entire original deserialized discovery document.
  739. schema: Object, mapping of schema names to schema descriptions.
  740. Returns:
  741. Tuple (path_url, http_method, method_id, accept, max_size, media_path_url)
  742. where:
  743. - path_url is a String; the relative URL for the API method. Relative to
  744. the API root, which is specified in the discovery document.
  745. - http_method is a String; the HTTP method used to call the API method
  746. described in the method description.
  747. - method_id is a String; the name of the RPC method associated with the
  748. API method, and is in the method description in the 'id' key.
  749. - accept is a list of strings representing what content types are
  750. accepted for media upload. Defaults to empty list if not in the
  751. discovery document.
  752. - max_size is a long representing the max size in bytes allowed for a
  753. media upload. Defaults to 0L if not in the discovery document.
  754. - media_path_url is a String; the absolute URI for media upload for the
  755. API method. Constructed using the API root URI and service path from
  756. the discovery document and the relative path for the API method. If
  757. media upload is not supported, this is None.
  758. """
  759. path_url = method_desc["path"]
  760. http_method = method_desc["httpMethod"]
  761. method_id = method_desc["id"]
  762. parameters = _fix_up_parameters(method_desc, root_desc, http_method, schema)
  763. # Order is important. `_fix_up_media_upload` needs `method_desc` to have a
  764. # 'parameters' key and needs to know if there is a 'body' parameter because it
  765. # also sets a 'media_body' parameter.
  766. accept, max_size, media_path_url = _fix_up_media_upload(
  767. method_desc, root_desc, path_url, parameters
  768. )
  769. return path_url, http_method, method_id, accept, max_size, media_path_url
  770. def _fix_up_media_path_base_url(media_path_url, base_url):
  771. """
  772. Update the media upload base url if its netloc doesn't match base url netloc.
  773. This can happen in case the base url was overridden by
  774. client_options.api_endpoint.
  775. Args:
  776. media_path_url: String; the absolute URI for media upload.
  777. base_url: string, base URL for the API. All requests are relative to this URI.
  778. Returns:
  779. String; the absolute URI for media upload.
  780. """
  781. parsed_media_url = urllib.parse.urlparse(media_path_url)
  782. parsed_base_url = urllib.parse.urlparse(base_url)
  783. if parsed_media_url.netloc == parsed_base_url.netloc:
  784. return media_path_url
  785. return urllib.parse.urlunparse(
  786. parsed_media_url._replace(netloc=parsed_base_url.netloc)
  787. )
  788. def _urljoin(base, url):
  789. """Custom urljoin replacement supporting : before / in url."""
  790. # In general, it's unsafe to simply join base and url. However, for
  791. # the case of discovery documents, we know:
  792. # * base will never contain params, query, or fragment
  793. # * url will never contain a scheme or net_loc.
  794. # In general, this means we can safely join on /; we just need to
  795. # ensure we end up with precisely one / joining base and url. The
  796. # exception here is the case of media uploads, where url will be an
  797. # absolute url.
  798. if url.startswith("http://") or url.startswith("https://"):
  799. return urllib.parse.urljoin(base, url)
  800. new_base = base if base.endswith("/") else base + "/"
  801. new_url = url[1:] if url.startswith("/") else url
  802. return new_base + new_url
  803. # TODO(dhermes): Convert this class to ResourceMethod and make it callable
  804. class ResourceMethodParameters(object):
  805. """Represents the parameters associated with a method.
  806. Attributes:
  807. argmap: Map from method parameter name (string) to query parameter name
  808. (string).
  809. required_params: List of required parameters (represented by parameter
  810. name as string).
  811. repeated_params: List of repeated parameters (represented by parameter
  812. name as string).
  813. pattern_params: Map from method parameter name (string) to regular
  814. expression (as a string). If the pattern is set for a parameter, the
  815. value for that parameter must match the regular expression.
  816. query_params: List of parameters (represented by parameter name as string)
  817. that will be used in the query string.
  818. path_params: Set of parameters (represented by parameter name as string)
  819. that will be used in the base URL path.
  820. param_types: Map from method parameter name (string) to parameter type. Type
  821. can be any valid JSON schema type; valid values are 'any', 'array',
  822. 'boolean', 'integer', 'number', 'object', or 'string'. Reference:
  823. http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
  824. enum_params: Map from method parameter name (string) to list of strings,
  825. where each list of strings is the list of acceptable enum values.
  826. """
  827. def __init__(self, method_desc):
  828. """Constructor for ResourceMethodParameters.
  829. Sets default values and defers to set_parameters to populate.
  830. Args:
  831. method_desc: Dictionary with metadata describing an API method. Value
  832. comes from the dictionary of methods stored in the 'methods' key in
  833. the deserialized discovery document.
  834. """
  835. self.argmap = {}
  836. self.required_params = []
  837. self.repeated_params = []
  838. self.pattern_params = {}
  839. self.query_params = []
  840. # TODO(dhermes): Change path_params to a list if the extra URITEMPLATE
  841. # parsing is gotten rid of.
  842. self.path_params = set()
  843. self.param_types = {}
  844. self.enum_params = {}
  845. self.set_parameters(method_desc)
  846. def set_parameters(self, method_desc):
  847. """Populates maps and lists based on method description.
  848. Iterates through each parameter for the method and parses the values from
  849. the parameter dictionary.
  850. Args:
  851. method_desc: Dictionary with metadata describing an API method. Value
  852. comes from the dictionary of methods stored in the 'methods' key in
  853. the deserialized discovery document.
  854. """
  855. parameters = method_desc.get("parameters", {})
  856. sorted_parameters = OrderedDict(sorted(parameters.items()))
  857. for arg, desc in sorted_parameters.items():
  858. param = key2param(arg)
  859. self.argmap[param] = arg
  860. if desc.get("pattern"):
  861. self.pattern_params[param] = desc["pattern"]
  862. if desc.get("enum"):
  863. self.enum_params[param] = desc["enum"]
  864. if desc.get("required"):
  865. self.required_params.append(param)
  866. if desc.get("repeated"):
  867. self.repeated_params.append(param)
  868. if desc.get("location") == "query":
  869. self.query_params.append(param)
  870. if desc.get("location") == "path":
  871. self.path_params.add(param)
  872. self.param_types[param] = desc.get("type", "string")
  873. # TODO(dhermes): Determine if this is still necessary. Discovery based APIs
  874. # should have all path parameters already marked with
  875. # 'location: path'.
  876. for match in URITEMPLATE.finditer(method_desc["path"]):
  877. for namematch in VARNAME.finditer(match.group(0)):
  878. name = key2param(namematch.group(0))
  879. self.path_params.add(name)
  880. if name in self.query_params:
  881. self.query_params.remove(name)
  882. def createMethod(methodName, methodDesc, rootDesc, schema):
  883. """Creates a method for attaching to a Resource.
  884. Args:
  885. methodName: string, name of the method to use.
  886. methodDesc: object, fragment of deserialized discovery document that
  887. describes the method.
  888. rootDesc: object, the entire deserialized discovery document.
  889. schema: object, mapping of schema names to schema descriptions.
  890. """
  891. methodName = fix_method_name(methodName)
  892. (
  893. pathUrl,
  894. httpMethod,
  895. methodId,
  896. accept,
  897. maxSize,
  898. mediaPathUrl,
  899. ) = _fix_up_method_description(methodDesc, rootDesc, schema)
  900. parameters = ResourceMethodParameters(methodDesc)
  901. def method(self, **kwargs):
  902. # Don't bother with doc string, it will be over-written by createMethod.
  903. for name in kwargs:
  904. if name not in parameters.argmap:
  905. raise TypeError("Got an unexpected keyword argument {}".format(name))
  906. # Remove args that have a value of None.
  907. keys = list(kwargs.keys())
  908. for name in keys:
  909. if kwargs[name] is None:
  910. del kwargs[name]
  911. for name in parameters.required_params:
  912. if name not in kwargs:
  913. # temporary workaround for non-paging methods incorrectly requiring
  914. # page token parameter (cf. drive.changes.watch vs. drive.changes.list)
  915. if name not in _PAGE_TOKEN_NAMES or _findPageTokenName(
  916. _methodProperties(methodDesc, schema, "response")
  917. ):
  918. raise TypeError('Missing required parameter "%s"' % name)
  919. for name, regex in parameters.pattern_params.items():
  920. if name in kwargs:
  921. if isinstance(kwargs[name], str):
  922. pvalues = [kwargs[name]]
  923. else:
  924. pvalues = kwargs[name]
  925. for pvalue in pvalues:
  926. if re.match(regex, pvalue) is None:
  927. raise TypeError(
  928. 'Parameter "%s" value "%s" does not match the pattern "%s"'
  929. % (name, pvalue, regex)
  930. )
  931. for name, enums in parameters.enum_params.items():
  932. if name in kwargs:
  933. # We need to handle the case of a repeated enum
  934. # name differently, since we want to handle both
  935. # arg='value' and arg=['value1', 'value2']
  936. if name in parameters.repeated_params and not isinstance(
  937. kwargs[name], str
  938. ):
  939. values = kwargs[name]
  940. else:
  941. values = [kwargs[name]]
  942. for value in values:
  943. if value not in enums:
  944. raise TypeError(
  945. 'Parameter "%s" value "%s" is not an allowed value in "%s"'
  946. % (name, value, str(enums))
  947. )
  948. actual_query_params = {}
  949. actual_path_params = {}
  950. for key, value in kwargs.items():
  951. to_type = parameters.param_types.get(key, "string")
  952. # For repeated parameters we cast each member of the list.
  953. if key in parameters.repeated_params and type(value) == type([]):
  954. cast_value = [_cast(x, to_type) for x in value]
  955. else:
  956. cast_value = _cast(value, to_type)
  957. if key in parameters.query_params:
  958. actual_query_params[parameters.argmap[key]] = cast_value
  959. if key in parameters.path_params:
  960. actual_path_params[parameters.argmap[key]] = cast_value
  961. body_value = kwargs.get("body", None)
  962. media_filename = kwargs.get("media_body", None)
  963. media_mime_type = kwargs.get("media_mime_type", None)
  964. if self._developerKey:
  965. actual_query_params["key"] = self._developerKey
  966. model = self._model
  967. if methodName.endswith("_media"):
  968. model = MediaModel()
  969. elif "response" not in methodDesc:
  970. model = RawModel()
  971. headers = {}
  972. headers, params, query, body = model.request(
  973. headers, actual_path_params, actual_query_params, body_value
  974. )
  975. expanded_url = uritemplate.expand(pathUrl, params)
  976. url = _urljoin(self._baseUrl, expanded_url + query)
  977. resumable = None
  978. multipart_boundary = ""
  979. if media_filename:
  980. # Ensure we end up with a valid MediaUpload object.
  981. if isinstance(media_filename, str):
  982. if media_mime_type is None:
  983. logger.warning(
  984. "media_mime_type argument not specified: trying to auto-detect for %s",
  985. media_filename,
  986. )
  987. media_mime_type, _ = mimetypes.guess_type(media_filename)
  988. if media_mime_type is None:
  989. raise UnknownFileType(media_filename)
  990. if not mimeparse.best_match([media_mime_type], ",".join(accept)):
  991. raise UnacceptableMimeTypeError(media_mime_type)
  992. media_upload = MediaFileUpload(media_filename, mimetype=media_mime_type)
  993. elif isinstance(media_filename, MediaUpload):
  994. media_upload = media_filename
  995. else:
  996. raise TypeError("media_filename must be str or MediaUpload.")
  997. # Check the maxSize
  998. if media_upload.size() is not None and media_upload.size() > maxSize > 0:
  999. raise MediaUploadSizeError("Media larger than: %s" % maxSize)
  1000. # Use the media path uri for media uploads
  1001. expanded_url = uritemplate.expand(mediaPathUrl, params)
  1002. url = _urljoin(self._baseUrl, expanded_url + query)
  1003. url = _fix_up_media_path_base_url(url, self._baseUrl)
  1004. if media_upload.resumable():
  1005. url = _add_query_parameter(url, "uploadType", "resumable")
  1006. if media_upload.resumable():
  1007. # This is all we need to do for resumable, if the body exists it gets
  1008. # sent in the first request, otherwise an empty body is sent.
  1009. resumable = media_upload
  1010. else:
  1011. # A non-resumable upload
  1012. if body is None:
  1013. # This is a simple media upload
  1014. headers["content-type"] = media_upload.mimetype()
  1015. body = media_upload.getbytes(0, media_upload.size())
  1016. url = _add_query_parameter(url, "uploadType", "media")
  1017. else:
  1018. # This is a multipart/related upload.
  1019. msgRoot = MIMEMultipart("related")
  1020. # msgRoot should not write out it's own headers
  1021. setattr(msgRoot, "_write_headers", lambda self: None)
  1022. # attach the body as one part
  1023. msg = MIMENonMultipart(*headers["content-type"].split("/"))
  1024. msg.set_payload(body)
  1025. msgRoot.attach(msg)
  1026. # attach the media as the second part
  1027. msg = MIMENonMultipart(*media_upload.mimetype().split("/"))
  1028. msg["Content-Transfer-Encoding"] = "binary"
  1029. payload = media_upload.getbytes(0, media_upload.size())
  1030. msg.set_payload(payload)
  1031. msgRoot.attach(msg)
  1032. # encode the body: note that we can't use `as_string`, because
  1033. # it plays games with `From ` lines.
  1034. fp = io.BytesIO()
  1035. g = _BytesGenerator(fp, mangle_from_=False)
  1036. g.flatten(msgRoot, unixfrom=False)
  1037. body = fp.getvalue()
  1038. multipart_boundary = msgRoot.get_boundary()
  1039. headers["content-type"] = (
  1040. "multipart/related; " 'boundary="%s"'
  1041. ) % multipart_boundary
  1042. url = _add_query_parameter(url, "uploadType", "multipart")
  1043. logger.debug("URL being requested: %s %s" % (httpMethod, url))
  1044. return self._requestBuilder(
  1045. self._http,
  1046. model.response,
  1047. url,
  1048. method=httpMethod,
  1049. body=body,
  1050. headers=headers,
  1051. methodId=methodId,
  1052. resumable=resumable,
  1053. )
  1054. docs = [methodDesc.get("description", DEFAULT_METHOD_DOC), "\n\n"]
  1055. if len(parameters.argmap) > 0:
  1056. docs.append("Args:\n")
  1057. # Skip undocumented params and params common to all methods.
  1058. skip_parameters = list(rootDesc.get("parameters", {}).keys())
  1059. skip_parameters.extend(STACK_QUERY_PARAMETERS)
  1060. all_args = list(parameters.argmap.keys())
  1061. args_ordered = [key2param(s) for s in methodDesc.get("parameterOrder", [])]
  1062. # Move body to the front of the line.
  1063. if "body" in all_args:
  1064. args_ordered.append("body")
  1065. for name in sorted(all_args):
  1066. if name not in args_ordered:
  1067. args_ordered.append(name)
  1068. for arg in args_ordered:
  1069. if arg in skip_parameters:
  1070. continue
  1071. repeated = ""
  1072. if arg in parameters.repeated_params:
  1073. repeated = " (repeated)"
  1074. required = ""
  1075. if arg in parameters.required_params:
  1076. required = " (required)"
  1077. paramdesc = methodDesc["parameters"][parameters.argmap[arg]]
  1078. paramdoc = paramdesc.get("description", "A parameter")
  1079. if "$ref" in paramdesc:
  1080. docs.append(
  1081. (" %s: object, %s%s%s\n The object takes the form of:\n\n%s\n\n")
  1082. % (
  1083. arg,
  1084. paramdoc,
  1085. required,
  1086. repeated,
  1087. schema.prettyPrintByName(paramdesc["$ref"]),
  1088. )
  1089. )
  1090. else:
  1091. paramtype = paramdesc.get("type", "string")
  1092. docs.append(
  1093. " %s: %s, %s%s%s\n" % (arg, paramtype, paramdoc, required, repeated)
  1094. )
  1095. enum = paramdesc.get("enum", [])
  1096. enumDesc = paramdesc.get("enumDescriptions", [])
  1097. if enum and enumDesc:
  1098. docs.append(" Allowed values\n")
  1099. for (name, desc) in zip(enum, enumDesc):
  1100. docs.append(" %s - %s\n" % (name, desc))
  1101. if "response" in methodDesc:
  1102. if methodName.endswith("_media"):
  1103. docs.append("\nReturns:\n The media object as a string.\n\n ")
  1104. else:
  1105. docs.append("\nReturns:\n An object of the form:\n\n ")
  1106. docs.append(schema.prettyPrintSchema(methodDesc["response"]))
  1107. setattr(method, "__doc__", "".join(docs))
  1108. return (methodName, method)
  1109. def createNextMethod(
  1110. methodName,
  1111. pageTokenName="pageToken",
  1112. nextPageTokenName="nextPageToken",
  1113. isPageTokenParameter=True,
  1114. ):
  1115. """Creates any _next methods for attaching to a Resource.
  1116. The _next methods allow for easy iteration through list() responses.
  1117. Args:
  1118. methodName: string, name of the method to use.
  1119. pageTokenName: string, name of request page token field.
  1120. nextPageTokenName: string, name of response page token field.
  1121. isPageTokenParameter: Boolean, True if request page token is a query
  1122. parameter, False if request page token is a field of the request body.
  1123. """
  1124. methodName = fix_method_name(methodName)
  1125. def methodNext(self, previous_request, previous_response):
  1126. """Retrieves the next page of results.
  1127. Args:
  1128. previous_request: The request for the previous page. (required)
  1129. previous_response: The response from the request for the previous page. (required)
  1130. Returns:
  1131. A request object that you can call 'execute()' on to request the next
  1132. page. Returns None if there are no more items in the collection.
  1133. """
  1134. # Retrieve nextPageToken from previous_response
  1135. # Use as pageToken in previous_request to create new request.
  1136. nextPageToken = previous_response.get(nextPageTokenName, None)
  1137. if not nextPageToken:
  1138. return None
  1139. request = copy.copy(previous_request)
  1140. if isPageTokenParameter:
  1141. # Replace pageToken value in URI
  1142. request.uri = _add_query_parameter(
  1143. request.uri, pageTokenName, nextPageToken
  1144. )
  1145. logger.debug("Next page request URL: %s %s" % (methodName, request.uri))
  1146. else:
  1147. # Replace pageToken value in request body
  1148. model = self._model
  1149. body = model.deserialize(request.body)
  1150. body[pageTokenName] = nextPageToken
  1151. request.body = model.serialize(body)
  1152. request.body_size = len(request.body)
  1153. if "content-length" in request.headers:
  1154. del request.headers["content-length"]
  1155. logger.debug("Next page request body: %s %s" % (methodName, body))
  1156. return request
  1157. return (methodName, methodNext)
  1158. class Resource(object):
  1159. """A class for interacting with a resource."""
  1160. def __init__(
  1161. self,
  1162. http,
  1163. baseUrl,
  1164. model,
  1165. requestBuilder,
  1166. developerKey,
  1167. resourceDesc,
  1168. rootDesc,
  1169. schema,
  1170. ):
  1171. """Build a Resource from the API description.
  1172. Args:
  1173. http: httplib2.Http, Object to make http requests with.
  1174. baseUrl: string, base URL for the API. All requests are relative to this
  1175. URI.
  1176. model: googleapiclient.Model, converts to and from the wire format.
  1177. requestBuilder: class or callable that instantiates an
  1178. googleapiclient.HttpRequest object.
  1179. developerKey: string, key obtained from
  1180. https://code.google.com/apis/console
  1181. resourceDesc: object, section of deserialized discovery document that
  1182. describes a resource. Note that the top level discovery document
  1183. is considered a resource.
  1184. rootDesc: object, the entire deserialized discovery document.
  1185. schema: object, mapping of schema names to schema descriptions.
  1186. """
  1187. self._dynamic_attrs = []
  1188. self._http = http
  1189. self._baseUrl = baseUrl
  1190. self._model = model
  1191. self._developerKey = developerKey
  1192. self._requestBuilder = requestBuilder
  1193. self._resourceDesc = resourceDesc
  1194. self._rootDesc = rootDesc
  1195. self._schema = schema
  1196. self._set_service_methods()
  1197. def _set_dynamic_attr(self, attr_name, value):
  1198. """Sets an instance attribute and tracks it in a list of dynamic attributes.
  1199. Args:
  1200. attr_name: string; The name of the attribute to be set
  1201. value: The value being set on the object and tracked in the dynamic cache.
  1202. """
  1203. self._dynamic_attrs.append(attr_name)
  1204. self.__dict__[attr_name] = value
  1205. def __getstate__(self):
  1206. """Trim the state down to something that can be pickled.
  1207. Uses the fact that the instance variable _dynamic_attrs holds attrs that
  1208. will be wiped and restored on pickle serialization.
  1209. """
  1210. state_dict = copy.copy(self.__dict__)
  1211. for dynamic_attr in self._dynamic_attrs:
  1212. del state_dict[dynamic_attr]
  1213. del state_dict["_dynamic_attrs"]
  1214. return state_dict
  1215. def __setstate__(self, state):
  1216. """Reconstitute the state of the object from being pickled.
  1217. Uses the fact that the instance variable _dynamic_attrs holds attrs that
  1218. will be wiped and restored on pickle serialization.
  1219. """
  1220. self.__dict__.update(state)
  1221. self._dynamic_attrs = []
  1222. self._set_service_methods()
  1223. def __enter__(self):
  1224. return self
  1225. def __exit__(self, exc_type, exc, exc_tb):
  1226. self.close()
  1227. def close(self):
  1228. """Close httplib2 connections."""
  1229. # httplib2 leaves sockets open by default.
  1230. # Cleanup using the `close` method.
  1231. # https://github.com/httplib2/httplib2/issues/148
  1232. self._http.close()
  1233. def _set_service_methods(self):
  1234. self._add_basic_methods(self._resourceDesc, self._rootDesc, self._schema)
  1235. self._add_nested_resources(self._resourceDesc, self._rootDesc, self._schema)
  1236. self._add_next_methods(self._resourceDesc, self._schema)
  1237. def _add_basic_methods(self, resourceDesc, rootDesc, schema):
  1238. # If this is the root Resource, add a new_batch_http_request() method.
  1239. if resourceDesc == rootDesc:
  1240. batch_uri = "%s%s" % (
  1241. rootDesc["rootUrl"],
  1242. rootDesc.get("batchPath", "batch"),
  1243. )
  1244. def new_batch_http_request(callback=None):
  1245. """Create a BatchHttpRequest object based on the discovery document.
  1246. Args:
  1247. callback: callable, A callback to be called for each response, of the
  1248. form callback(id, response, exception). The first parameter is the
  1249. request id, and the second is the deserialized response object. The
  1250. third is an apiclient.errors.HttpError exception object if an HTTP
  1251. error occurred while processing the request, or None if no error
  1252. occurred.
  1253. Returns:
  1254. A BatchHttpRequest object based on the discovery document.
  1255. """
  1256. return BatchHttpRequest(callback=callback, batch_uri=batch_uri)
  1257. self._set_dynamic_attr("new_batch_http_request", new_batch_http_request)
  1258. # Add basic methods to Resource
  1259. if "methods" in resourceDesc:
  1260. for methodName, methodDesc in resourceDesc["methods"].items():
  1261. fixedMethodName, method = createMethod(
  1262. methodName, methodDesc, rootDesc, schema
  1263. )
  1264. self._set_dynamic_attr(
  1265. fixedMethodName, method.__get__(self, self.__class__)
  1266. )
  1267. # Add in _media methods. The functionality of the attached method will
  1268. # change when it sees that the method name ends in _media.
  1269. if methodDesc.get("supportsMediaDownload", False):
  1270. fixedMethodName, method = createMethod(
  1271. methodName + "_media", methodDesc, rootDesc, schema
  1272. )
  1273. self._set_dynamic_attr(
  1274. fixedMethodName, method.__get__(self, self.__class__)
  1275. )
  1276. def _add_nested_resources(self, resourceDesc, rootDesc, schema):
  1277. # Add in nested resources
  1278. if "resources" in resourceDesc:
  1279. def createResourceMethod(methodName, methodDesc):
  1280. """Create a method on the Resource to access a nested Resource.
  1281. Args:
  1282. methodName: string, name of the method to use.
  1283. methodDesc: object, fragment of deserialized discovery document that
  1284. describes the method.
  1285. """
  1286. methodName = fix_method_name(methodName)
  1287. def methodResource(self):
  1288. return Resource(
  1289. http=self._http,
  1290. baseUrl=self._baseUrl,
  1291. model=self._model,
  1292. developerKey=self._developerKey,
  1293. requestBuilder=self._requestBuilder,
  1294. resourceDesc=methodDesc,
  1295. rootDesc=rootDesc,
  1296. schema=schema,
  1297. )
  1298. setattr(methodResource, "__doc__", "A collection resource.")
  1299. setattr(methodResource, "__is_resource__", True)
  1300. return (methodName, methodResource)
  1301. for methodName, methodDesc in resourceDesc["resources"].items():
  1302. fixedMethodName, method = createResourceMethod(methodName, methodDesc)
  1303. self._set_dynamic_attr(
  1304. fixedMethodName, method.__get__(self, self.__class__)
  1305. )
  1306. def _add_next_methods(self, resourceDesc, schema):
  1307. # Add _next() methods if and only if one of the names 'pageToken' or
  1308. # 'nextPageToken' occurs among the fields of both the method's response
  1309. # type either the method's request (query parameters) or request body.
  1310. if "methods" not in resourceDesc:
  1311. return
  1312. for methodName, methodDesc in resourceDesc["methods"].items():
  1313. nextPageTokenName = _findPageTokenName(
  1314. _methodProperties(methodDesc, schema, "response")
  1315. )
  1316. if not nextPageTokenName:
  1317. continue
  1318. isPageTokenParameter = True
  1319. pageTokenName = _findPageTokenName(methodDesc.get("parameters", {}))
  1320. if not pageTokenName:
  1321. isPageTokenParameter = False
  1322. pageTokenName = _findPageTokenName(
  1323. _methodProperties(methodDesc, schema, "request")
  1324. )
  1325. if not pageTokenName:
  1326. continue
  1327. fixedMethodName, method = createNextMethod(
  1328. methodName + "_next",
  1329. pageTokenName,
  1330. nextPageTokenName,
  1331. isPageTokenParameter,
  1332. )
  1333. self._set_dynamic_attr(
  1334. fixedMethodName, method.__get__(self, self.__class__)
  1335. )
  1336. def _findPageTokenName(fields):
  1337. """Search field names for one like a page token.
  1338. Args:
  1339. fields: container of string, names of fields.
  1340. Returns:
  1341. First name that is either 'pageToken' or 'nextPageToken' if one exists,
  1342. otherwise None.
  1343. """
  1344. return next(
  1345. (tokenName for tokenName in _PAGE_TOKEN_NAMES if tokenName in fields), None
  1346. )
  1347. def _methodProperties(methodDesc, schema, name):
  1348. """Get properties of a field in a method description.
  1349. Args:
  1350. methodDesc: object, fragment of deserialized discovery document that
  1351. describes the method.
  1352. schema: object, mapping of schema names to schema descriptions.
  1353. name: string, name of top-level field in method description.
  1354. Returns:
  1355. Object representing fragment of deserialized discovery document
  1356. corresponding to 'properties' field of object corresponding to named field
  1357. in method description, if it exists, otherwise empty dict.
  1358. """
  1359. desc = methodDesc.get(name, {})
  1360. if "$ref" in desc:
  1361. desc = schema.get(desc["$ref"], {})
  1362. return desc.get("properties", {})