本文整理汇总了Python中treq.content方法的典型用法代码示例。如果您正苦于以下问题:Python treq.content方法的具体用法?Python treq.content怎么用?Python treq.content使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类treq
的用法示例。
在下文中一共展示了treq.content方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_and_decode_json
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def check_and_decode_json(result, response_code):
"""
Given ``treq`` response object, extract JSON and ensure response code
is the expected one.
:param result: ``treq`` response.
:param int response_code: Expected response code.
:return: ``Deferred`` firing with decoded JSON.
"""
def error(body):
raise ResponseError(result.code, body)
if result.code != response_code:
d = content(result)
d.addCallback(error)
return d
return json_content(result)
示例2: create_container
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def create_container(self, properties):
"""
Create a container with the specified properties.
:param dict properties: A ``dict`` mapping to the API request fields
to create a container.
:returns: A ``Deferred`` which fires with an API response when the
container with the supplied properties has been persisted to the
cluster configuration.
"""
request = self.treq.post(
self.base_url + b"/configuration/containers",
data=dumps(properties),
headers={b"content-type": b"application/json"},
)
request.addCallback(check_and_decode_json, CREATED)
return request
示例3: move_container
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def move_container(self, name, node_uuid):
"""
Move a container.
:param unicode name: The name of the container to move.
:param unicode node_uuid: The UUID to which the container should
be moved.
:returns: A ``Deferred`` which fires with an API response when the
container move has been persisted to the cluster configuration.
"""
request = self.treq.post(
self.base_url + b"/configuration/containers/" +
name.encode("ascii"),
data=dumps({u"node_uuid": node_uuid}),
headers={b"content-type": b"application/json"},
)
request.addCallback(check_and_decode_json, OK)
return request
示例4: test_content_length_post_hook
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def test_content_length_post_hook(self):
"""
When the content length is changed by a post-hook, test that powerstrip returns the
correct content as per the content-length
"""
d = self._hookTest("""endpoints:
"POST %(dockerEndpoint)s":
pre: []
post: [adder,adder,adder,adder,adder,adder,adder,adder,adder]
adapters:
adder: http://127.0.0.1:%(adderPort)d%(adapterEndpoint)s""", adderArgs=dict(post=True))
def verify(response):
self.assertEqual(response,
{"Number": 10, "SeenByFakeDocker": 42})
d.addCallback(verify)
return d
示例5: test_stream_endpoint
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def test_stream_endpoint(self):
"""
A streaming (aka hijacking) endpoint like /attach is permitted with no
post-hooks (the Docker response's content-type is detected and the
entire connection switched down into simple TCP-proxying mode (with
support for half-close).
"""
self._configure("endpoints: {}\nadapters: {}", dockerArgs=dict(rawStream=True))
d = self.client.post('http://127.0.0.1:%d/towel' % (self.proxyPort,),
json.dumps({"raw": "stream"}),
headers={'Content-Type': ['application/json']})
def verify(response):
self.assertEqual(response.headers.getRawHeaders("content-type"),
["application/vnd.docker.raw-stream"])
# TODO Verify that half-close, and bi-directional TCP proxying
# works.
d.addCallback(verify)
return d
示例6: test_adder_explode
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def test_adder_explode(self):
"""
The adder adapter blows up (sends an HTTP 500) when asked to.
"""
self._getAdder(explode=True)
d = self.client.post('http://127.0.0.1:%d/adapter' % (self.adderPort,),
json.dumps({}),
headers={'Content-Type': ['application/json']})
def verifyResponseCode(response):
self.assertEqual(response.code, 500)
return response
d.addCallback(verifyResponseCode)
d.addCallback(treq.content)
def verify(body):
self.assertEqual(body, "sadness for you, today.")
d.addCallback(verify)
return d
示例7: get_grid_status
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def get_grid_status(self):
if not self.nodeurl:
return None
try:
resp = yield treq.get(self.nodeurl + "?t=json")
except ConnectError:
return None
if resp.code == 200:
content = yield treq.content(resp)
content = json.loads(content.decode("utf-8"))
servers_connected = 0
servers_known = 0
available_space = 0
if "servers" in content:
servers = content["servers"]
servers_known = len(servers)
for server in servers:
if server["connection_status"].startswith("Connected"):
servers_connected += 1
if server["available_space"]:
available_space += server["available_space"]
return servers_connected, servers_known, available_space
return None
示例8: unlink
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def unlink(self, dircap, childname):
dircap_hash = trunchash(dircap)
log.debug('Unlinking "%s" from %s...', childname, dircap_hash)
yield self.await_ready()
yield self.lock.acquire()
try:
resp = yield treq.post(
"{}uri/{}/?t=unlink&name={}".format(
self.nodeurl, dircap, childname
)
)
finally:
yield self.lock.release()
if resp.code != 200:
content = yield treq.content(resp)
raise TahoeWebError(content.decode("utf-8"))
log.debug('Done unlinking "%s" from %s', childname, dircap_hash)
示例9: get_magic_folders_from_rootcap
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def get_magic_folders_from_rootcap(self, content=None):
if not content:
content = yield self.get_json(self.get_rootcap())
if content:
folders = defaultdict(dict)
for name, data in content[1]["children"].items():
data_dict = data[1]
if name.endswith(" (collective)"):
prefix = name.split(" (collective)")[0]
folders[prefix]["collective_dircap"] = data_dict["ro_uri"]
elif name.endswith(" (personal)"):
prefix = name.split(" (personal)")[0]
folders[prefix]["upload_dircap"] = data_dict["rw_uri"]
elif name.endswith(" (admin)"):
prefix = name.split(" (admin)")[0]
folders[prefix]["admin_dircap"] = data_dict["rw_uri"]
self.remote_magic_folders = folders
return folders
return None
示例10: get_magic_folder_members
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def get_magic_folder_members(self, name, content=None):
if not content:
content = yield self.get_json(self.get_collective_dircap(name))
if content:
members = []
children = content[1]["children"]
magic_folder_dircap = self.get_magic_folder_dircap(name)
for member in children:
readcap = children[member][1]["ro_uri"]
if magic_folder_dircap:
my_fingerprint = magic_folder_dircap.split(":")[-1]
fingerprint = readcap.split(":")[-1]
if fingerprint == my_fingerprint:
self.magic_folders[name]["member"] = member
members.insert(0, (member, readcap))
else:
members.append((member, readcap))
else:
members.append((member, readcap))
return members
return None
示例11: post_http_server
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def post_http_server(test, host, port, data, expected_response=b"ok"):
"""
Make a POST request to an HTTP server on the given host and port
and assert that the response body matches the expected response.
:param bytes host: Host to connect to.
:param int port: Port to connect to.
:param bytes data: The raw request body data.
:param bytes expected_response: The HTTP response body expected.
Defaults to b"ok"
"""
def make_post(host, port, data):
request = post(
"http://{host}:{port}".format(host=host, port=port),
data=data,
timeout=SOCKET_TIMEOUT_FOR_POLLING,
persistent=False,
)
def failed(failure):
Message.new(message_type=u"acceptance:http_query_failed",
reason=unicode(failure)).write()
return False
request.addCallbacks(content, failed)
return request
d = verify_socket(host, port)
d.addCallback(lambda _: loop_until(reactor, lambda: make_post(
host, port, data)))
d.addCallback(test.assertEqual, expected_response)
return d
示例12: query_http_server
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def query_http_server(host, port, path=b""):
"""
Return the response from a HTTP server.
We try multiple since it may take a little time for the HTTP
server to start up.
:param bytes host: Host to connect to.
:param int port: Port to connect to.
:param bytes path: Optional path and query string.
:return: ``Deferred`` that fires with the body of the response.
"""
def query():
req = get(
"http://{host}:{port}{path}".format(
host=host, port=port, path=path),
timeout=SOCKET_TIMEOUT_FOR_POLLING,
persistent=False,
)
def failed(failure):
Message.new(message_type=u"acceptance:http_query_failed",
reason=unicode(failure)).write()
return False
req.addCallbacks(content, failed)
return req
d = verify_socket(host, port)
d.addCallback(lambda _: loop_until(reactor, query))
return d
示例13: test_command_line
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def test_command_line(self):
"""
A container with custom command line is run with those arguments.
"""
external_port = find_free_port()[1]
name = random_name(self)
d = self.start_container(
name, image_name=u"busybox",
# Pass in pvector since this likely to be what caller actually
# passes in:
command_line=pvector([u"sh", u"-c", u"""\
echo -n '#!/bin/sh
echo -n "HTTP/1.1 200 OK\r\n\r\nhi"
' > /tmp/script.sh;
chmod +x /tmp/script.sh;
nc -ll -p 8080 -e /tmp/script.sh
"""]),
ports=[PortMap(internal_port=8080,
external_port=external_port)])
d.addCallback(
lambda ignored: self.request_until_response(external_port))
def started(response):
d = content(response)
d.addCallback(lambda body: self.assertEqual(b"hi", body))
return d
d.addCallback(started)
return d
示例14: check_upstream_response
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def check_upstream_response(response, request):
content = yield treq.content(response)
if response.code != 200:
request.setResponseCode(502)
defer.returnValue("Upstream response code: {:d}\n{!s}".format(response.code, content))
else:
defer.returnValue(content)
示例15: get_userinfo_by_email
# 需要导入模块: import treq [as 别名]
# 或者: from treq import content [as 别名]
def get_userinfo_by_email(self, email):
deferred = self.get('/users/name/{:s}'.format(email.split('@')[0]))
deferred.addCallback(check_userinfo_response, email)
deferred.addCallback(treq.content)
deferred.addCallback(json.loads)
return deferred