Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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)
def query_server():
req = get(
"http://{host}:12345".format(host=node.public_address),
persistent=False
).addCallbacks(content)
return req
def get_connected_servers(self):
if not self.nodeurl:
return None
try:
resp = yield treq.get(self.nodeurl)
except ConnectError:
return None
if resp.code == 200:
html = yield treq.content(resp)
match = re.search(
"Connected to <span>(.+?)</span>", html.decode("utf-8")
)
if match:
return int(match.group(1))
return None
def get(self, url, raw_content=False):
url = self.url + url
headers = {
"MARKET-KEY": self.public_key,
"MARKET-TOKEN": self.token,
"Content-Type": "application/json"
}
resp = yield treq.get(url, headers=headers)
if raw_content:
content = yield treq.content(resp)
return content
data = yield treq.json_content(resp)
return data
def get_magic_folder_status(self, name):
if not self.nodeurl or not self.api_token:
return None
try:
resp = yield treq.post(
self.nodeurl + "magic_folder",
{"token": self.api_token, "name": name, "t": "json"},
)
except ConnectError:
return None
if resp.code == 200:
content = yield treq.content(resp)
return json.loads(content.decode("utf-8"))
return None
def download(self, cap, local_path):
log.debug("Downloading %s...", local_path)
yield self.await_ready()
resp = yield treq.get("{}uri/{}".format(self.nodeurl, cap))
if resp.code == 200:
with atomic_write(local_path, mode="wb", overwrite=True) as f:
yield treq.collect(resp, f.write)
log.debug("Successfully downloaded %s", local_path)
else:
content = yield treq.content(resp)
raise TahoeWebError(content.decode("utf-8"))
def mkdir(self, parentcap=None, childname=None):
yield self.await_ready()
url = self.nodeurl + "uri"
params = {"t": "mkdir"}
if parentcap and childname:
url += "/" + parentcap
params["name"] = childname
resp = yield treq.post(url, params=params)
if resp.code == 200:
content = yield treq.content(resp)
return content.decode("utf-8").strip()
raise TahoeWebError(
"Error creating Tahoe-LAFS directory: {}".format(resp.code)
)
def perform_request_with_treq(dispatcher, http_request):
"""A performer for :obj:`HTTPRequest` that uses the ``treq`` library."""
headers = (
http_request.headers.copy()
if http_request.headers is not None
else {})
if 'user-agent' not in headers:
headers['user-agent'] = ['Effect example']
d = treq.request(
http_request.method.lower(),
http_request.url,
headers=headers,
data=http_request.data).addCallback(treq.content)
return d
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)
logger.info(
"{%s} [%s] Got response headers: %d %s",
request.txn_id,
request.destination,
response.code,
response.phrase.decode("ascii", errors="replace"),
)
set_tag(tags.HTTP_STATUS_CODE, response.code)
if 200 <= response.code < 300:
pass
else:
# :'(
# Update transactions table?
d = treq.content(response)
d = timeout_deferred(
d, timeout=_sec_timeout, reactor=self.reactor
)
try:
body = yield make_deferred_yieldable(d)
except Exception as e:
# Eh, we're already going to raise an exception so lets
# ignore if this fails.
logger.warning(
"{%s} [%s] Failed to get error response: %s %s: %s",
request.txn_id,
request.destination,
request.method,
url_str,
_flatten_response_never_received(e),