本文整理汇总了Python中uritemplate.expand方法的典型用法代码示例。如果您正苦于以下问题:Python uritemplate.expand方法的具体用法?Python uritemplate.expand怎么用?Python uritemplate.expand使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类uritemplate
的用法示例。
在下文中一共展示了uritemplate.expand方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _refresh
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def _refresh(self, http_request):
"""Refreshes the access_token.
Skip all the storage hoops and just refresh using the API.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
uri = uritemplate.expand(META, {'scope': self.scope})
response, content = http_request(uri)
if response.status == 200:
try:
d = simplejson.loads(content)
except StandardError, e:
raise AccessTokenRefreshError(str(e))
self.access_token = d['accessToken']
示例2: _prepare_request
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def _prepare_request(self, url: str, var_dict: Mapping[str, str],
data: Any = None,
charset: str = 'utf-8',
accept: str = "application/json") -> Tuple[str, Mapping[str, str], bytes]:
"""Prepare url, headers and json body for request"""
url = uritemplate.expand(url, var_dict=var_dict)
headers = {}
headers['accept'] = accept
headers['Authorization'] = "Bearer " + self.token
body = b''
if isinstance(data, str):
body = data.encode(charset)
elif isinstance(data, Mapping):
body = json.dumps(data).encode(charset)
headers['content-type'] = "application/json; charset=" + charset
headers['content-length'] = str(len(body))
return url, headers, body
示例3: _make_request
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def _make_request(self, method: str, url: str, var_dict: Mapping[str, str],
data: Any = None,
accept: str = "application/json") -> Any:
"""Make HTTP request"""
url = ''.join((self.CIRCLE_API, url, "{?circle-token}"))
url = uritemplate.expand(url, var_dict=var_dict)
headers = {}
headers['accept'] = accept
charset = 'utf-8'
body = b''
if isinstance(data, str):
body = data.encode(charset)
elif isinstance(data, Mapping):
body = json.dumps(data).encode(charset)
headers['content-type'] = "application/json; charset=" + charset
headers['content-length'] = str(len(body))
status, res_headers, response = await self._request(method, url, headers, body)
if self.debug_once:
self.debug_once = False
logger.error("Called %s / %s", method, url)
logger.error("Headers: %s", headers)
logger.error("Body: %s", body)
logger.error("Result Status: %s", status)
logger.error("Result Headers: %s", res_headers)
logger.error("Response: %s", response.decode(charset))
if status == 404:
logger.error("Got 404 for %s", url)
return []
response_text = response.decode(charset)
try:
return json.loads(response_text)
except json.decoder.JSONDecodeError as exc:
logger.error("Call to '%s' yielded text '%s' - not JSON",
url.replace(self.token, "******"),
response_text.replace(self.token, "******"))
return response_text
示例4: get_gcs_client
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def get_gcs_client(self) -> luigi.contrib.gcs.GCSClient:
if (not os.path.isfile(self.discover_cache_local_path)):
with open(self.discover_cache_local_path, "w") as f:
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
params = {"api": "storage", "apiVersion": "v1"}
discovery_http = build_http()
for discovery_url in (self._DISCOVERY_URI, self._V2_DISCOVERY_URI):
requested_url = uritemplate.expand(discovery_url, params)
try:
content = _retrieve_discovery_doc(
requested_url, discovery_http, False
)
except HttpError as e:
if e.resp.status == http_client.NOT_FOUND:
continue
else:
raise e
break
f.write(content)
fcntl.flock(f, fcntl.LOCK_UN)
except IOError:
# try to read
pass
with open(self.discover_cache_local_path, "r") as f:
fcntl.flock(f, fcntl.LOCK_SH)
descriptor = f.read()
fcntl.flock(f, fcntl.LOCK_UN)
return luigi.contrib.gcs.GCSClient(oauth_credentials=self._load_oauth_credentials(), descriptor=descriptor)
示例5: main
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def main():
'''Main logic'''
import argparse
parser = argparse.ArgumentParser('Create GitHub relase')
parser.add_argument('--token', '-t', required=True,
help='GitHub authentication token')
parser.add_argument('--user', '-u', required=True,
help='GitHub user account')
parser.add_argument('--repo', '-r', required=True,
help='GitHub repo name')
parser.add_argument('--version', '-v', required=True,
help='Version to create')
parser.add_argument('--file', '-f',
help='File to upload to release')
parser.add_argument('--content-type', '-c',
help='Content type of file')
args = parser.parse_args()
api_url = 'https://api.github.com/repos/{user}/{repo}/releases'
api_url = api_url.format(user=args.user, repo=args.repo)
# Create release
release_json = create_release(api_url, args.token, args.version)
# Upload file
if args.file:
upload_url = expand(release_json['upload_url'],
{'name': os.path.basename(args.file)})
upload_file(upload_url, args.token, args.file, args.content_type)
示例6: _build_resource_link
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def _build_resource_link(self, **kwargs):
"""Build a full URI for a specific resource.
Args:
**kwargs: The args to expand in the URI template.
Returns:
str: The Resource URI
Raises:
ValueError: Raised if the resource_path_template parameter was
undefined when the repository was created.
"""
expanded_url = uritemplate.expand(self._resource_path_template, kwargs)
return urljoin(self.gcp_service._baseUrl, expanded_url) # pylint: disable=protected-access
示例7: format_url
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def format_url(url: str, url_vars: Mapping[str, Any], *, base_url: str = DOMAIN) -> str:
"""Construct a URL for the GitHub API.
The URL may be absolute or relative. In the latter case the appropriate
domain will be added. This is to help when copying the relative URL directly
from the GitHub developer documentation.
The dict provided in url_vars is used in URI template formatting.
"""
url = urllib.parse.urljoin(base_url, url) # Works even if 'url' is fully-qualified.
expanded_url: str = uritemplate.expand(url, var_dict=url_vars)
return expanded_url
示例8: build
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def build(serviceName,
version,
http=None,
discoveryServiceUrl=DISCOVERY_URI,
developerKey=None,
model=None,
requestBuilder=HttpRequest,
credentials=None,
cache_discovery=True,
cache=None):
"""Construct a Resource for interacting with an API.
Construct a Resource object for interacting with an API. The serviceName and
version are the names from the Discovery service.
Args:
serviceName: string, name of the service.
version: string, the version of the service.
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
discoveryServiceUrl: string, a URI Template that points to the location of
the discovery service. It should have two parameters {api} and
{apiVersion} that when filled in produce an absolute URI to the discovery
document for that service.
developerKey: string, key obtained from
https://code.google.com/apis/console.
model: googleapiclient.Model, converts to and from the wire format.
requestBuilder: googleapiclient.http.HttpRequest, encapsulator for an HTTP
request.
credentials: oauth2client.Credentials, credentials to be used for
authentication.
cache_discovery: Boolean, whether or not to cache the discovery doc.
cache: googleapiclient.discovery_cache.base.CacheBase, an optional
cache object for the discovery documents.
Returns:
A Resource object with methods for interacting with the service.
"""
params = {
'api': serviceName,
'apiVersion': version
}
if http is None:
http = httplib2.Http()
requested_url = uritemplate.expand(discoveryServiceUrl, params)
try:
content = _retrieve_discovery_doc(requested_url, http, cache_discovery,
cache)
except HttpError as e:
if e.resp.status == http_client.NOT_FOUND:
raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
version))
else:
raise e
return build_from_document(content, base=discoveryServiceUrl, http=http,
developerKey=developerKey, model=model, requestBuilder=requestBuilder,
credentials=credentials)
示例9: get_tile
# 需要导入模块: import uritemplate [as 别名]
# 或者: from uritemplate import expand [as 别名]
def get_tile(zoom, x, y, data_url_template=None):
''' Get a single Tile instance.
zoom, x, y: Web mercator tile coordinates using OpenStreetMap convention.
https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Zoom_levels
data_url_template: RFC 6570 URI template for upstream protobuf tiles
with z, x, y, and layer expressions. Default to DATA_URL_TEMPLATE.
https://tools.ietf.org/html/rfc6570#section-2.2)
'''
if data_url_template is None:
data_url_template = DATA_URL_TEMPLATE
# Define lat/lon for filtered area
tile_coord = ModestMaps.Core.Coordinate(y, x, zoom)
data_coord = tile_coord.zoomTo(DATA_ZOOM).container()
tile_sw = OSM.coordinateLocation(tile_coord.down())
tile_ne = OSM.coordinateLocation(tile_coord.right())
data_zxy = dict(z=int(data_coord.zoom), x=int(data_coord.column), y=int(data_coord.row))
logger.debug((tile_coord, data_coord, tile_sw, tile_ne))
# Filter geometries within the selected tile
geom_data_url = uritemplate.expand(data_url_template, layer='geometry', **data_zxy)
geometries = {geom.id: geom for geom in iter_objects(geom_data_url,
data_classes['geometry']) if is_inside(tile_sw, tile_ne, geom)}
logger.debug('{} geometries'.format(len(geometries)))
# Get intersections attached to one of the filtered geometries
inter_data_url = uritemplate.expand(data_url_template, layer='intersection', **data_zxy)
intersection_ids = {id for id in itertools.chain(*[(geom.fromIntersectionId,
geom.toIntersectionId) for geom in geometries.values()])}
intersections = {inter.id: inter for inter in iter_objects(inter_data_url,
data_classes['intersection']) if inter.id in intersection_ids}
logger.debug('{} intersections'.format(len(intersections)))
# Get references attached to one of the filtered geometries
ref_data_url = uritemplate.expand(data_url_template, layer='reference', **data_zxy)
references = {ref.id: ref for ref in iter_objects(ref_data_url,
data_classes['reference']) if ref.geometryId in geometries}
logger.debug('{} references'.format(len(references)))
# Get metadata attached to one of the filtered geometries
md_data_url = uritemplate.expand(data_url_template, layer='metadata', **data_zxy)
metadata = {md.geometryId: md for md in iter_objects(md_data_url,
data_classes['metadata']) if md.geometryId in geometries}
logger.debug('{} metadata'.format(len(metadata)))
return Tile(geometries, intersections, references, metadata)