本文整理汇总了Python中yarl.URL.with_query方法的典型用法代码示例。如果您正苦于以下问题:Python URL.with_query方法的具体用法?Python URL.with_query怎么用?Python URL.with_query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yarl.URL
的用法示例。
在下文中一共展示了URL.with_query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_with_query_only_single_arg_is_supported
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_only_single_arg_is_supported():
url = URL("http://example.com")
u1 = url.with_query(b=3)
u2 = URL("http://example.com/?b=3")
assert u1 == u2
with pytest.raises(ValueError):
url.with_query("a=1", "a=b")
示例2: url_for
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def url_for(self, *, filename, append_version=None):
if append_version is None:
append_version = self._append_version
if isinstance(filename, Path):
filename = str(filename)
while filename.startswith('/'):
filename = filename[1:]
filename = '/' + filename
url = self._prefix + URL(filename).raw_path
url = URL(url)
if append_version is True:
try:
if filename.startswith('/'):
filename = filename[1:]
filepath = self._directory.joinpath(filename).resolve()
if not self._follow_symlinks:
filepath.relative_to(self._directory)
except (ValueError, FileNotFoundError):
# ValueError for case when path point to symlink
# with follow_symlinks is False
return url # relatively safe
if filepath.is_file():
# TODO cache file content
# with file watcher for cache invalidation
with open(str(filepath), mode='rb') as f:
file_bytes = f.read()
h = self._get_file_hash(file_bytes)
url = url.with_query({self.VERSION_KEY: h})
return url
return url
示例3: request
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def request(self, method, url, *,
auth=None,
status=200,
text=None,
data=None,
content=None,
json=None,
params=None,
headers={},
exc=None,
cookies=None):
"""Mock a request."""
if json is not None:
text = _json.dumps(json)
if text is not None:
content = text.encode('utf-8')
if content is None:
content = b''
if not isinstance(url, retype):
url = URL(url)
if params:
url = url.with_query(params)
self._mocks.append(AiohttpClientMockResponse(
method, url, status, content, cookies, exc, headers))
示例4: maker
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def maker(method, path, query_params={}, headers=None, match_info=None, loop=None):
path = URL(path)
if query_params:
path = path.with_query(query_params)
if headers is None:
headers = CIMultiDict(
{
"HOST": "server.example.com",
"UPGRADE": "websocket",
"CONNECTION": "Upgrade",
"SEC-WEBSOCKET-KEY": "dGhlIHNhbXBsZSBub25jZQ==",
"ORIGIN": "http://example.com",
"SEC-WEBSOCKET-PROTOCOL": "chat, superchat",
"SEC-WEBSOCKET-VERSION": "13",
}
)
writer = mock.Mock()
writer.write_headers = make_mocked_coro(None)
writer.write = make_mocked_coro(None)
writer.drain = make_mocked_coro(None)
transport = mock.Mock()
transport._drain_helper = make_mocked_coro()
ret = make_mocked_request(method, str(path), headers, writer=writer, loop=loop)
if match_info is None:
match_info = UrlMappingMatchInfo({}, mock.Mock())
match_info.add_app(app)
ret._match_info = match_info
return ret
示例5: aget
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def aget(self, **kw):
session = aiohttp.ClientSession()
url = URL(self.url)
if kw:
url = url.with_query(**kw)
logger.debug("GET %s", url)
try:
response = yield from session.get(url, timeout=10)
payload = yield from response.read()
finally:
yield from session.close()
response.raise_for_status()
payload = payload.decode('utf-8')
if response.content_type == 'text/x-python':
payload = ast.literal_eval(payload)
return Payload.factory(response.status, response.headers, payload)
示例6: apost
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def apost(self, headers={}, data=None, **kw):
session = aiohttp.ClientSession()
url = URL(self.url)
if kw:
url = url.with_query(**kw)
logger.debug("POST %s", url)
try:
response = yield from session.post(
url, headers=headers, data=data, timeout=10,
)
payload = yield from response.read()
finally:
yield from session.close()
response.raise_for_status()
payload = payload.decode('utf-8')
return Payload.factory(response.status, response.headers, payload)
示例7: match_request
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
async def match_request(self, method, url, *, data=None, auth=None,
params=None, headers=None, allow_redirects=None,
timeout=None, json=None):
"""Match a request against pre-registered requests."""
data = data or json
url = URL(url)
if params:
url = url.with_query(params)
for response in self._mocks:
if response.match_request(method, url, params):
self.mock_calls.append((method, url, data, headers))
if response.exc:
raise response.exc
return response
assert False, "No mock registered for {} {} {}".format(method.upper(),
url, params)
示例8: test_with_query_str
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_str():
url = URL("http://example.com")
assert str(url.with_query("a=1&b=2")) == "http://example.com/?a=1&b=2"
示例9: test_with_query_str_non_ascii_and_spaces
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_str_non_ascii_and_spaces():
url = URL("http://example.com")
url2 = url.with_query("a=1 2&b=знач")
assert url2.raw_query_string == "a=1+2&b=%D0%B7%D0%BD%D0%B0%D1%87"
assert url2.query_string == "a=1 2&b=знач"
示例10: test_with_query_empty_str
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_empty_str():
url = URL("http://example.com/?a=b")
assert str(url.with_query("")) == "http://example.com/"
示例11: test_with_query_empty_value
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_empty_value():
url = URL("http://example.com/")
assert str(url.with_query({"a": ""})) == "http://example.com/?a="
示例12: test_with_query_bytearray
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_bytearray():
url = URL("http://example.com")
with pytest.raises(TypeError):
url.with_query(bytearray(b"123"))
示例13: test_with_query_empty_dict
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def test_with_query_empty_dict():
url = URL("http://example.com/?a=b")
new_url = url.with_query({})
assert new_url.query_string == ""
assert str(new_url) == "http://example.com/"
示例14: __init__
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
class TestServer:
def __init__(self, app, *, scheme="http", host='127.0.0.1'):
self.app = app
self._loop = app.loop
self.port = None
self.server = None
self.handler = None
self._root = None
self.host = host
self.scheme = scheme
self._closed = False
@asyncio.coroutine
def start_server(self, **kwargs):
if self.server:
return
self.port = unused_port()
self._root = URL('{}://{}:{}'.format(self.scheme,
self.host,
self.port))
self.handler = self.app.make_handler(**kwargs)
self.server = yield from self._loop.create_server(self.handler,
self.host,
self.port)
def make_url(self, path):
assert path.startswith('/')
path = path[1:]
if path.startswith('?'):
# add a query to root path
return self._root.with_query(path[1:])
else:
return self._root / path
@asyncio.coroutine
def close(self):
"""Close all fixtures created by the test client.
After that point, the TestClient is no longer usable.
This is an idempotent function: running close multiple times
will not have any additional effects.
close is also run when the object is garbage collected, and on
exit when used as a context manager.
"""
if self.server is not None and not self._closed:
self.server.close()
yield from self.server.wait_closed()
yield from self.app.shutdown()
yield from self.handler.finish_connections()
yield from self.app.cleanup()
self._root = None
self.port = None
self._closed = True
def __enter__(self):
self._loop.run_until_complete(self.start_server())
return self
def __exit__(self, exc_type, exc_value, traceback):
self._loop.run_until_complete(self.close())
if PY_35:
@asyncio.coroutine
def __aenter__(self):
yield from self.start_server()
return self
@asyncio.coroutine
def __aexit__(self, exc_type, exc_value, traceback):
yield from self.close()
示例15: _crawl_resource_list
# 需要导入模块: from yarl import URL [as 别名]
# 或者: from yarl.URL import with_query [as 别名]
def _crawl_resource_list(self, url: URL) -> List[URL]:
zero_url = url.with_query({"limit": 0, "offset": 0})
count = self._crawl(zero_url, save=False)["count"]
full_url = url.with_query({"limit": count, "offset": 0})
resource_list = self._crawl(full_url)
return [URL(resource_ref["url"]) for resource_ref in resource_list["results"]]