本文整理汇总了Python中urlobject.URLObject.add_path方法的典型用法代码示例。如果您正苦于以下问题:Python URLObject.add_path方法的具体用法?Python URLObject.add_path怎么用?Python URLObject.add_path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urlobject.URLObject
的用法示例。
在下文中一共展示了URLObject.add_path方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: API
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
class API(object):
def __init__(self, client, url):
super(API, self).__init__()
self.client = client
self.url = URL(url)
def call_function(self, name, params=None):
resp = requests.post(
self.url.add_path('api').add_path(name),
data=self._serialize_params(params),
headers={'Content-type': 'application/json'},
)
resp.raise_for_status()
return self._normalize_return_value(resp)
def get(self, path, raw=False):
resp = requests.get(self.url.add_path(path))
resp.raise_for_status()
if raw:
return resp.json()
else:
return self._normalize_return_value(resp)
def _normalize_return_value(self, response):
result = response.json()['result']
if result is None:
return None
assert isinstance(result, dict) and 'type' in result
return self.build_api_object(result)
def build_api_object(self, result):
return self._get_objtype(result)(self.client, result)
def _get_objtype(self, json_object):
typename = json_object['type']
returned = _TYPES_BY_TYPENAME.get(typename)
if returned is None:
raise NotImplementedError() # pragma: no cover
return returned
def _serialize_params(self, params):
if params is None:
params = {}
returned = {}
for param_name, param_value in iteritems(params):
if param_value is NOTHING:
continue
returned[param_name] = param_value
return json.dumps(returned)
示例2: App
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
class App(object):
def __init__(self, flask_app):
super(App, self).__init__()
self.flask_app = flask_app
self.loopback = FlaskLoopback(self.flask_app)
self.hostname = str(uuid1())
self.url = URLObject("http://{0}".format(self.hostname))
def activate(self):
self.loopback.activate_address((self.hostname, 80))
def deactivate(self):
self.loopback.deactivate_address((self.hostname, 80))
def get_page(self, page_size, page, path=None):
if path is None:
path = "objects"
response = requests.get(self.url.add_path(path).set_query_param("page", str(page)).set_query_param("page_size", str(page_size)))
response.raise_for_status()
data = response.json()
assert data["metadata"]["page"] == page
assert data["metadata"]["page_size"] == page_size
return data["result"]
def get_all_paged(self, page_size, path=None):
return list(itertools.chain.from_iterable(self.get_page(page_size, page, path=path) for page in range(1, int(self.num_objects / page_size) + 5)))
示例3: KeystoneAuth
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
class KeystoneAuth(object):
def __init__(self, identity_url, username, password):
self._identity_url = URLObject(identity_url)
self._username = username
self._password = password
self._session = requests.Session()
self._session.headers = {
"content-type": "application/json",
"accept": "application/json"
}
self._auth_token = None
self._service_catalog = None
def _perform_auth_request(self):
auth_response = self._session.post(
self._identity_url.add_path('tokens'),
data=json.dumps({
"auth": {
"passwordCredentials": {
"username": self._username,
"password": self._password
}
},
"tenantId": " "
})
)
auth_response.raise_for_status()
auth_body = auth_response.json()
self._auth_token = auth_body["access"]["token"]["id"]
self._service_catalog = ServiceCatalog(
auth_body["access"]["serviceCatalog"]
)
def _handle_request_result(self, response, **kwargs):
if response.status_code == 401:
# We got an authentication failure, get a new token and try again.
self._perform_auth_request()
new_request = response.request.copy()
new_request.headers["X-Auth-Token"] = self._auth_token
new_response = response.connection.send(new_request, **kwargs)
new_response.history.append(response)
new_response.request = new_request
return new_response
else:
return response
def __call__(self, request):
if self._auth_token is None:
self._perform_auth_request()
request.headers['X-Auth-Token'] = self._auth_token
request.register_hook("response", self._handle_request_result)
return request
@property
def service_catalog(self):
if self._service_catalog is None:
self._perform_auth_request()
return self._service_catalog
示例4: _join_path
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
def _join_path(url, path):
_url = URL(url)
path = URL(path)
if path.path:
_url = _url.add_path(path.path)
if path.query:
_url = _url.with_query(path.query)
return _url
示例5: url_join
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
def url_join(base, *paths):
"""
Append `paths` to `base`. Path resets on each absolute path.
Like os.path.join, but for URLs.
"""
if not hasattr(base, 'add_path'):
base = URLObject(base)
for path in paths:
path = URLPath(path)
base = base.add_path(path)
return base
示例6: Mailboxer
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
class Mailboxer(object):
def __init__(self, url):
super(Mailboxer, self).__init__()
self.url = URL(url).add_path("v2")
def create_mailbox(self, address):
self._post(self.url.add_path("mailboxes"), {"address": address})
return Mailbox(self, address)
def delete_mailbox(self, address):
return self.get_mailbox(address).delete()
def get_emails(self, address, unread = False):
return self.get_mailbox(address).get_emails(unread)
def get_mailboxes(self, **kwargs):
return Query(self, self.url.add_path("mailboxes"), Mailbox, **kwargs)
def get_mailbox(self, address):
return Mailbox(self, address)
def does_mailbox_exist(self, address):
return Mailbox(self, address).exists()
def _post(self, url, data):
returned = requests.post(url, data=json.dumps(data),
headers={"Content-type": "application/json"})
returned.raise_for_status()
return returned
def _get_paged(self, url, obj):
response = requests.get(url)
response.raise_for_status()
return [obj(data) for data in response.json()["result"]]
def _mailbox_url(self, address):
return self.url.add_path("mailboxes").add_path(address)
示例7: fetch_token
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
def fetch_token(self, username, password):
url = URL(self._get_backslash_url())
with requests.Session() as s:
resp = s.get(self._get_token_request_url())
resp.raise_for_status()
response_url = resp.json()['url']
request_id = response_url.split('/')[-1]
s.post(url.add_path('login'),
data=json.dumps({'username': username, 'password': password}),
headers={'Content-type': 'application/json'})\
.raise_for_status()
s.post(URL(self._get_backslash_url()).add_path('/runtoken/request/{}/complete'.format(request_id)))\
.raise_for_status()
resp = s.get(response_url)
resp.raise_for_status()
returned = self._runtoken = resp.json()['token']
return returned
示例8: test_add_path_adds_a_partial_path
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
def test_add_path_adds_a_partial_path(self):
url = URLObject('https://github.com/zacharyvoase/urlobject')
assert (url.add_path('tree') ==
'https://github.com/zacharyvoase/urlobject/tree')
assert (url.add_path('tree/master') ==
'https://github.com/zacharyvoase/urlobject/tree/master')
示例9: SpurlURLBuilder
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
#.........这里部分代码省略.........
current_query = self.url.query.dict
for key, value in list(query_to_toggle.items()):
if isinstance(value, six.string_types):
value = value.split(',')
first, second = value
if key in current_query and first in current_query[key]:
self.url = self.url.set_query_param(key, second)
else:
self.url = self.url.set_query_param(key, first)
def handle_scheme(self, value):
self.url = self.url.with_scheme(value)
def handle_scheme_from(self, value):
url = URLObject(value)
self.url = self.url.with_scheme(url.scheme)
def handle_host(self, value):
host = self.prepare_value(value)
self.url = self.url.with_hostname(host)
def handle_host_from(self, value):
url = URLObject(value)
self.url = self.url.with_hostname(url.hostname)
def handle_path(self, value):
path = self.prepare_value(value)
self.url = self.url.with_path(path)
def handle_path_from(self, value):
url = URLObject(value)
self.url = self.url.with_path(url.path)
def handle_add_path(self, value):
path_to_add = self.prepare_value(value)
self.url = self.url.add_path(path_to_add)
def handle_add_path_from(self, value):
url = URLObject(value)
path_to_add = url.path
if path_to_add.startswith('/'):
path_to_add = path_to_add[1:]
self.url = self.url.add_path(path_to_add)
def handle_fragment(self, value):
fragment = self.prepare_value(value)
self.url = self.url.with_fragment(fragment)
def handle_fragment_from(self, value):
url = URLObject(value)
self.url = self.url.with_fragment(url.fragment)
def handle_port(self, value):
self.url = self.url.with_port(int(value))
def handle_port_from(self, value):
url = URLObject(value)
self.url = self.url.with_port(url.port)
def handle_autoescape(self, value):
self.autoescape = convert_to_boolean(value)
def set_sensible_defaults(self):
if self.url.hostname and not self.url.scheme:
self.url = self.url.with_scheme('http')
示例10: SpurlURLBuilder
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
#.........这里部分代码省略.........
if ext and len(ext) > 1:
if key in current_query and value in ext:
active = True
self.url = active
def handle_scheme(self, value):
self.url = self.url.with_scheme(value)
def handle_scheme_from(self, value):
url = URLObject(value)
self.url = self.url.with_scheme(url.scheme)
def handle_host(self, value):
host = self.prepare_value(value)
self.url = self.url.with_hostname(host)
def handle_host_from(self, value):
url = URLObject(value)
self.url = self.url.with_hostname(url.hostname)
def handle_path(self, value):
path = self.prepare_value(value)
self.url = self.url.with_path(path)
def handle_path_from(self, value):
url = URLObject(value)
self.url = self.url.with_path(url.path)
def handle_add_path(self, value):
path_to_add = self.prepare_value(value)
self.url = self.url.add_path(path_to_add)
def handle_add_path_from(self, value):
url = URLObject(value)
path_to_add = url.path
if path_to_add.startswith('/'):
path_to_add = path_to_add[1:]
self.url = self.url.add_path(path_to_add)
def handle_fragment(self, value):
fragment = self.prepare_value(value)
self.url = self.url.with_fragment(fragment)
def handle_fragment_from(self, value):
url = URLObject(value)
self.url = self.url.with_fragment(url.fragment)
def handle_port(self, value):
self.url = self.url.with_port(int(value))
def handle_port_from(self, value):
url = URLObject(value)
self.url = self.url.with_port(url.port)
def handle_autoescape(self, value):
self.autoescape = convert_to_boolean(value)
def set_sensible_defaults(self):
if self.url.hostname and not self.url.scheme:
self.url = self.url.with_scheme('http')
示例11: API
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import add_path [as 别名]
class API(object):
def __init__(self, client, url, runtoken, timeout_seconds=60):
super(API, self).__init__()
self.client = client
self.url = URL(url)
self.runtoken = runtoken
self.session = requests.Session()
self.session.headers.update({
'X-Backslash-run-token': self.runtoken,
'X-Backslash-client-version': BACKSLASH_CLIENT_VERSION,
})
self.call = CallProxy(self)
self._cached_info = None
self._timeout = timeout_seconds
def __del__(self):
if self.session is not None:
self.session.close()
def info(self):
"""Inspects the remote API and returns information about its capabilities
"""
if self._cached_info is None:
resp = self.session.options(self.url.add_path('api'), timeout=self._timeout)
raise_for_status(resp)
self._cached_info = munchify(resp.json())
return copy.deepcopy(self._cached_info)
def call_function(self, name, params=None):
is_compressed, data = self._serialize_params(params)
headers = {'Content-type': 'application/json'}
if is_compressed:
headers['Content-encoding'] = 'gzip'
for _ in self._iter_retries():
try:
resp = self.session.post(
self.url.add_path('api').add_path(name), data=data, headers=headers, timeout=self._timeout)
except (ConnectionError, ReadTimeout, ):
continue
if resp.status_code not in _RETRY_STATUS_CODES:
break
else:
raise BackslashClientException(
'Maximum number of retries exceeded for calling Backslash API')
raise_for_status(resp)
return self._normalize_return_value(resp)
def _iter_retries(self, timeout=30, sleep_range=(3, 10)):
start_time = time.time()
end_time = start_time + timeout
while True:
yield
if time.time() < end_time:
time.sleep(random.randrange(*sleep_range))
def get(self, path, raw=False, params=None):
resp = self.session.get(self.url.add_path(path), params=params, timeout=self._timeout)
raise_for_status(resp)
if raw:
return resp.json()
else:
return self._normalize_return_value(resp)
def delete(self, path, params=None):
resp = self.session.delete(self.url.add_path(path), params=params, timeout=self._timeout)
raise_for_status(resp)
return resp
def _normalize_return_value(self, response):
json_res = response.json()
if json_res is None:
return None
result = json_res.get('result')
if result is None:
if isinstance(json_res, dict):
for key, value in json_res.items():
if isinstance(value, dict) and value.get('type') == key:
return self.build_api_object(value)
return json_res
elif isinstance(result, dict) and 'type' in result:
return self.build_api_object(result)
return result
def build_api_object(self, result):
objtype = self._get_objtype(result)
if objtype is None:
return result
return objtype(self.client, result)
def _get_objtype(self, json_object):
typename = json_object['type']
return _TYPES_BY_TYPENAME.get(typename)
def _serialize_params(self, params):
#.........这里部分代码省略.........