本文整理汇总了Python中urlobject.URLObject.with_path方法的典型用法代码示例。如果您正苦于以下问题:Python URLObject.with_path方法的具体用法?Python URLObject.with_path怎么用?Python URLObject.with_path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urlobject.URLObject
的用法示例。
在下文中一共展示了URLObject.with_path方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Session
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
class Session(object):
def __init__(self, nick, host, username, password, debug=False):
self.nick = nick
self.host = URLObject(host)
self.session = requests.Session()
self.session.auth = (username, password)
self.session.headers["Content-Type"] = "application/json"
self.debug = debug
self.count = 0
MSG_FMT = "{verb:4s} {nick:5s} {url}"
@property
def username(self):
return self.session.auth[0]
def get(self, url, *args, **kwargs):
if not isinstance(url, URLObject):
url = self.host.with_path(url)
if self.debug:
print(self.MSG_FMT.format(verb="GET", nick=self.nick, url=url))
self.count += 1
return self.session.get(url, *args, **kwargs)
def post(self, url, *args, **kwargs):
if not isinstance(url, URLObject):
url = self.host.with_path(url)
if self.debug:
print(self.MSG_FMT.format(verb="POST", nick=self.nick, url=url))
self.count += 1
return self.session.post(url, *args, **kwargs)
def put(self, url, *args, **kwargs):
if not isinstance(url, URLObject):
url = self.host.with_path(url)
if self.debug:
print(self.MSG_FMT.format(verb="PUT", nick=self.nick, url=url))
return self.session.put(url, *args, **kwargs)
def delete(self, url, *args, **kwargs):
if not isinstance(url, URLObject):
url = self.host.with_path(url)
if self.debug:
print(self.MSG_FMT.format(verb="DELETE", nick=self.nick, url=url))
return self.session.delete(url, *args, **kwargs)
示例2: URLObjectModificationTest
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
class URLObjectModificationTest(unittest.TestCase):
def setUp(self):
self.url = URLObject('https://github.com/zacharyvoase/urlobject?spam=eggs#foo')
def test_with_scheme_replaces_scheme(self):
assert (self.url.with_scheme('http') ==
'http://github.com/zacharyvoase/urlobject?spam=eggs#foo')
def test_with_netloc_replaces_netloc(self):
assert (self.url.with_netloc('example.com') ==
'https://example.com/zacharyvoase/urlobject?spam=eggs#foo')
def test_with_hostname_replaces_hostname(self):
url = URLObject('https://user:[email protected]/')
assert (url.with_hostname('example.com') ==
'https://user:[email protected]/')
def test_with_username_adds_username(self):
url = URLObject('https://github.com/')
assert url.with_username('zack') == 'https://[email protected]/'
def test_with_username_replaces_username(self):
url = URLObject('https://[email protected]/')
assert url.with_username('alice') == 'https://[email protected]/'
def test_without_username_removes_username(self):
url = URLObject('https://[email protected]/')
assert url.without_username() == 'https://github.com/'
def test_with_password_adds_password(self):
url = URLObject('https://[email protected]/')
assert url.with_password('1234') == 'https://zack:[email protected]/'
def test_with_password_raises_ValueError_when_there_is_no_username(self):
url = URLObject('https://github.com/')
assert_raises(ValueError, lambda: url.with_password('1234'))
def test_with_password_replaces_password(self):
url = URLObject('https://zack:[email protected]/')
assert url.with_password('5678') == 'https://zack:[email protected]/'
def test_without_password_removes_password(self):
url = URLObject('https://zack:[email protected]/')
assert url.without_password() == 'https://[email protected]/'
def test_with_auth_with_one_arg_adds_username(self):
url = URLObject('https://github.com/')
assert url.with_auth('zack') == 'https://[email protected]/'
def test_with_auth_with_one_arg_replaces_whole_auth_string_with_username(self):
url = URLObject('https://alice:[email protected]/')
assert url.with_auth('zack') == 'https://[email protected]/'
def test_with_auth_with_two_args_adds_username_and_password(self):
url = URLObject('https://github.com/')
assert url.with_auth('zack', '1234') == 'https://zack:[email protected]/'
def test_with_auth_with_two_args_replaces_whole_auth_string_with_username_and_password(self):
# Replaces username-only auth string
url = URLObject('https://[email protected]/')
assert url.with_auth('zack', '1234') == 'https://zack:[email protected]/'
# Replaces username and password.
url = URLObject('https://alice:[email protected]/')
assert url.with_auth('zack', '1234') == 'https://zack:[email protected]/'
def test_without_auth_removes_entire_auth_string(self):
# No username or password => no-op.
url = URLObject('https://github.com/')
assert url.without_auth() == 'https://github.com/'
# Username-only.
url = URLObject('https://[email protected]/')
assert url.without_auth() == 'https://github.com/'
# Username and password.
url = URLObject('https://alice:[email protected]/')
assert url.without_auth() == 'https://github.com/'
def test_with_port_adds_port_number(self):
assert (self.url.with_port(24) ==
'https://github.com:24/zacharyvoase/urlobject?spam=eggs#foo')
def test_with_port_replaces_port_number(self):
url = URLObject('https://github.com:59/')
assert url.with_port(67) == 'https://github.com:67/'
def test_without_port_removes_port_number(self):
url = URLObject('https://github.com:59/')
assert url.without_port() == 'https://github.com/'
def test_with_path_replaces_path(self):
assert (self.url.with_path('/dvxhouse/intessa') ==
'https://github.com/dvxhouse/intessa?spam=eggs#foo')
def test_root_goes_to_root_path(self):
assert self.url.root == 'https://github.com/?spam=eggs#foo'
def test_parent_jumps_up_one_level(self):
url = URLObject('https://github.com/zacharyvoase/urlobject')
assert url.parent == 'https://github.com/zacharyvoase/'
#.........这里部分代码省略.........
示例3: SpurlURLBuilder
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
#.........这里部分代码省略.........
self.url = self.url.del_query_param(query_to_remove)
def handle_toggle_query(self, value):
query_to_toggle = self.prepare_value(value)
if isinstance(query_to_toggle, six.string_types):
query_to_toggle = QueryString(query_to_toggle).dict
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):
示例4: issue_opened
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
def issue_opened(issue, bugsnag_context=None):
bugsnag_context = bugsnag_context or {}
bugsnag_context = {"issue": issue}
bugsnag.configure_request(meta_data=bugsnag_context)
issue_key = to_unicode(issue["key"])
issue_url = URLObject(issue["self"])
transitioned = False
if should_transition(issue):
# In JIRA, a "transition" is how an issue changes from one status
# to another, like going from "Open" to "In Progress". The workflow
# defines what transitions are allowed, and this API will tell us
# what transitions are currently allowed by the workflow.
# Ref: https://docs.atlassian.com/jira/REST/ondemand/#d2e4954
transitions_url = issue_url.with_path(issue_url.path + "/transitions")
transitions_resp = jira_get(transitions_url)
if not transitions_resp.ok:
raise requests.exceptions.RequestException(transitions_resp.text)
# This transforms the API response into a simple mapping from the
# name of the transition (like "In Progress") to the ID of the transition.
# Note that a transition may not have the same name as the state that it
# goes to, so a transition to go from "Open" to "In Progress" may be
# named something like "Start Work".
transitions = {t["name"]: t["id"] for t in transitions_resp.json()["transitions"]}
# We attempt to transition the issue into the "Open" state for the given project
# (some projects use a different name), so look for a transition with the right name
new_status = None
action = None
for state_name in ["Open", "Design Backlog", "To Do"]:
if state_name in transitions:
new_status = state_name
action = "Transitioned to '{}'".format(state_name)
if not new_status:
# If it's an OSPR subtask (used by teams to manage reviews), transition to team backlog
if to_unicode(issue["fields"]["project"]["key"]) == "OSPR" and issue["fields"]["issuetype"]["subtask"]:
new_status = "To Backlog"
action = "Transitioned to 'To Backlog'"
else:
raise ValueError("No valid transition! Possibilities are {}".format(transitions.keys()))
# This creates a new API request to tell JIRA to move the issue from
# one status to another using the specified transition. We have to
# tell JIRA the transition ID, so we use that mapping we set up earlier.
body = {
"transition": {
"id": transitions[new_status],
}
}
transition_resp = jira.post(transitions_url, json=body)
if not transition_resp.ok:
raise requests.exceptions.RequestException(transition_resp.text)
transitioned = True
# log to stderr
if transitioned and not action:
action = "Transitioned to Open"
else:
action = "ignored"
print(
"{key} created by {name} ({username}), {action}".format(
key=issue_key,
name=to_unicode(issue["fields"]["creator"]["displayName"]),
username=to_unicode(issue["fields"]["creator"]["name"]),
action="Transitioned to Open" if transitioned else "ignored",
),
file=sys.stderr,
)
return action
示例5: RawManager
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
class RawManager(object):
'''
The raw manager allows you to query the FileMaker web interface.
Most manager methods (the exceptions being the committing methods;
``find``, ``find_all``, ``edit``, ``new``, and ``delete``) are chainable,
enabling usage like
::
manager = RawManager(...)
manager = manager.filter(field=value).add_sort_param('some_field')
results = manager.find_all()
'''
def __init__(self, url, db, layout, response_layout=None, **kwargs):
'''
:param url: The URL to access the FileMaker server. This should contain
any authorization credentials. If a path is not provided (e.g. no
trailing slash, like ``http://username:[email protected]``) then
the default path of ``/fmi/xml/fmresultset.xml`` will be used.
:param db: The database name to access (sets the ``-db`` parameter).
:param layout: The layout to use (sets the ``-lay`` parameter).
:param response_layout: (*Optional*) The layout to use (sets the
``-lay.response`` parameter).
'''
self.url = URLObject(url).without_auth()
self.url = self.url.with_path(
self.url.path or '/fmi/xml/fmresultset.xml')
self.auth = URLObject(url).auth
self.params = QueryDict('', mutable=True)
self.dbparams = QueryDict('', mutable=True)
self.dbparams.update({
'-db': db,
'-lay': layout,
})
if response_layout:
self.dbparams['-lay.response'] = response_layout
self.params['-max'] = '50'
def __repr__(self):
return '<RawManager: {0} {1} {2}>'.format(
self.url, self.dbparams, self.params)
def _clone(self):
return copy.copy(self)
def set_script(self, name, option=None):
'''
Sets the name of the filemaker script to use
:param name: The name of the script to use.
:param option: (*Optional*) Can be one of ``presort`` or ``prefind``.
'''
mgr = self._clone()
key = '-script'
if option in ('prefind', 'presort'):
key = '{0}.{1}'.format(key, option)
mgr.params[key] = name
return mgr
def set_record_id(self, recid):
'''
Sets the ``-recid`` parameter.
:param recid: The record ID to set.
'''
mgr = self._clone()
mgr.params['-recid'] = recid
return mgr
def set_modifier_id(self, modid):
'''
Sets the ``-modid`` parameter.
:param modid: The modifier ID to set.
'''
mgr = self._clone()
mgr.params['-modid'] = modid
return mgr
def set_logical_operator(self, op):
'''
Set the logical operator to be used for this query using the ``-op``
parameter.
:param op: Must be one of ``and`` or ``or``.
'''
mgr = self._clone()
if op in ('and', 'or'):
mgr.params['-lop'] = op
return mgr
def set_group_size(self, max):
'''
Set the group size to return from FileMaker using the ``-max``.
This is defaulted to 50 when the manager is initialized.
:param integer max: The number of records to return.
'''
#.........这里部分代码省略.........
示例6: render
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
def render(self, context):
kwargs = MultiValueDict()
for key in self.kwargs:
key = smart_str(key, 'ascii')
values = [value.resolve(context) for value in self.kwargs.getlist(key)]
kwargs.setlist(key, values)
if 'base' in kwargs:
url = URLObject.parse(kwargs['base'])
else:
url = URLObject(scheme='http')
if 'secure' in kwargs:
if convert_to_boolean(kwargs['secure']):
url = url.with_scheme('https')
else:
url = url.with_scheme('http')
if 'query' in kwargs:
query = kwargs['query']
if isinstance(query, basestring):
query = render_template_from_string_without_autoescape(query, context)
url = url.with_query(query)
if 'add_query' in kwargs:
for query_to_add in kwargs.getlist('add_query'):
if isinstance(query_to_add, basestring):
query_to_add = render_template_from_string_without_autoescape(query_to_add, context)
query_to_add = dict(decode_query(query_to_add))
for key, value in query_to_add.items():
url = url.add_query_param(key, value)
if 'scheme' in kwargs:
url = url.with_scheme(kwargs['scheme'])
if 'host' in kwargs:
url = url.with_host(kwargs['host'])
if 'path' in kwargs:
url = url.with_path(kwargs['path'])
if 'add_path' in kwargs:
for path_to_add in kwargs.getlist('add_path'):
url = url.add_path_component(path_to_add)
if 'fragment' in kwargs:
url = url.with_fragment(kwargs['fragment'])
if 'port' in kwargs:
url = url.with_port(kwargs['port'])
# sensible default
if not url.host:
url = url.with_scheme('')
# Convert the URLObject to its unicode representation
url = unicode(url)
# Handle escaping. By default, use the value of
# context.autoescape. This can be overridden by
# passing an "autoescape" keyword to the tag.
if 'autoescape' in kwargs:
autoescape = convert_to_boolean(kwargs['autoescape'])
else:
autoescape = context.autoescape
if autoescape:
url = escape(url)
if self.asvar:
context[self.asvar] = url
return ''
return url
示例7: SpurlURLBuilder
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
#.........这里部分代码省略.........
# check if current query has multiple items
try:
ext = current_query[key]
ext = ext.split(',')
except Exception as e:
ext = None
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):
示例8: issue_opened
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
def issue_opened(issue, bugsnag_context=None):
bugsnag_context = bugsnag_context or {}
bugsnag_context = {"issue": issue}
bugsnag.configure_request(meta_data=bugsnag_context)
issue_key = issue["key"].decode('utf-8')
issue_status = issue["fields"]["status"]["name"].decode('utf-8')
project = issue["fields"]["project"]["key"].decode('utf-8')
if issue_status != "Needs Triage":
print(
"{key} has status {status}, does not need to be processed".format(
key=issue_key, status=issue_status,
),
file=sys.stderr,
)
return "issue does not need to be triaged"
if project == "OSPR":
# open source pull requests do not skip Needs Triage
print(
"{key} is an open source pull request, and does not need to be processed.".format(
key=issue_key
),
file=sys.stderr,
)
return "issue is OSPR"
issue_url = URLObject(issue["self"])
user_url = URLObject(issue["fields"]["creator"]["self"])
user_url = user_url.set_query_param("expand", "groups")
user_resp = jira_get(user_url)
if not user_resp.ok:
raise requests.exceptions.RequestException(user_resp.text)
user = user_resp.json()
groups = {g["name"]: g["self"] for g in user["groups"]["items"]}
# skip "Needs Triage" if bug was created by edX employee
transitioned = False
if "edx-employees" in groups:
transitions_url = issue_url.with_path(issue_url.path + "/transitions")
transitions_resp = jira_get(transitions_url)
if not transitions_resp.ok:
raise requests.exceptions.RequestException(transitions_resp.text)
transitions = {t["name"]: t["id"] for t in transitions_resp.json()["transitions"]}
if "Open" in transitions:
new_status = "Open"
elif "Design Backlog" in transitions:
new_status = "Design Backlog"
else:
raise ValueError("No valid transition! Possibilities are {}".format(transitions.keys()))
body = {
"transition": {
"id": transitions[new_status],
}
}
transition_resp = jira.post(transitions_url, json=body)
if not transition_resp.ok:
raise requests.exceptions.RequestException(transition_resp.text)
transitioned = True
try:
name = issue["fields"]["creator"]["displayName"].decode('utf-8')
except:
bugsnag_context["name_type"] = type(issue["fields"]["creator"]["displayName"])
bugsnag.configure_request(meta_data=bugsnag_context)
raise
# log to stderr
action = "Transitioned to Open" if transitioned else "ignored"
print(
"{key} created by {name} ({username}), {action}".format(
key=issue_key,
name=name,
username=issue["fields"]["creator"]["name"].decode('utf-8'),
action="Transitioned to Open" if transitioned else "ignored",
),
file=sys.stderr,
)
return action
示例9: jira_issue_created
# 需要导入模块: from urlobject import URLObject [as 别名]
# 或者: from urlobject.URLObject import with_path [as 别名]
def jira_issue_created():
"""
Received an "issue created" event from JIRA.
https://developer.atlassian.com/display/JIRADEV/JIRA+Webhooks+Overview
Ideally, this should be handled in a task queue, but we want to stay within
Heroku's free plan, so it will be handled inline instead.
(A worker dyno costs money.)
"""
try:
event = request.get_json()
except ValueError:
raise ValueError("Invalid JSON from JIRA: {data}".format(data=request.data))
bugsnag.configure_request(meta_data={"event": event})
if app.debug:
print(json.dumps(event), file=sys.stderr)
issue_key = event["issue"]["key"]
issue_status = event["issue"]["fields"]["status"]["name"]
project = event["issue"]["fields"]["project"]["key"]
if issue_status != "Needs Triage":
print(
"{key} has status {status}, does not need to be processed".format(
key=issue_key, status=issue_status,
),
file=sys.stderr,
)
return "issue does not need to be triaged"
if project == "OSPR":
# open source pull requests do not skip Needs Triage
print(
"{key} is an open source pull request, and does not need to be processed.".format(
key=issue_key
),
file=sys.stderr,
)
return "issue is OSPR"
issue_url = URLObject(event["issue"]["self"])
user_url = URLObject(event["user"]["self"])
user_url = user_url.set_query_param("expand", "groups")
user_resp = jira_get(user_url)
if not user_resp.ok:
raise requests.exceptions.RequestException(user_resp.text)
user = user_resp.json()
groups = {g["name"]: g["self"] for g in user["groups"]["items"]}
# skip "Needs Triage" if bug was created by edX employee
transitioned = False
if "edx-employees" in groups:
transitions_url = issue_url.with_path(issue_url.path + "/transitions")
transitions_resp = jira_get(transitions_url)
if not transitions_resp.ok:
raise requests.exceptions.RequestException(transitions_resp.text)
transitions = {t["name"]: t["id"] for t in transitions_resp.json()["transitions"]}
if "Open" in transitions:
new_status = "Open"
elif "Design Backlog" in transitions:
new_status = "Design Backlog"
else:
raise ValueError("No valid transition! Possibilities are {}".format(transitions.keys()))
body = {
"transition": {
"id": transitions[new_status],
}
}
transition_resp = jira.post(transitions_url, data=json.dumps(body))
if not transition_resp.ok:
raise requests.exceptions.RequestException(transition_resp.text)
transitioned = True
# log to stderr
print(
"{key} created by {name} ({username}), {action}".format(
key=issue_key, name=event["user"]["displayName"],
username=event["user"]["name"],
action="Transitioned to Open" if transitioned else "ignored",
),
file=sys.stderr,
)
return "Processed"