本文整理汇总了Python中requests.request方法的典型用法代码示例。如果您正苦于以下问题:Python requests.request方法的具体用法?Python requests.request怎么用?Python requests.request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def __init__(self, id=0, user=None, key=None, timeout=None):
"""
Initialize the base class.
You can provide `id` that is the item id used for url creation. You can also
provide `user`, that is the username for login.
You can also provide `key`, that is the userkey needed to
authenticate with the user, you can find it in the
[account info](http://thetvdb.com/?tab=userinfo) under account identifier.,
the language id you want to use to retrieve the info.
"""
self._ID = id
self.USER = user
"""Stores username if available"""
self.USER_KEY = key
"""Stores user-key if available"""
self.TIMEOUT = timeout
"""Stores timeout request if available"""
示例2: _request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def _request(self, method, path, params=None, payload=None,
forceNewToken=False, cleanJson=True):
self._set_token_header(forceNewToken)
url = self._get_complete_url(path)
response = requests.request(
method, url, params=params,
data=json.dumps(payload) if payload else payload,
headers=self._headers,
timeout=self.TIMEOUT)
if response.status_code == 200:
response.encoding = 'utf-8'
jsn = response.json()
if cleanJson and 'data' in jsn:
return jsn['data']
return jsn
elif not forceNewToken:
return self._request(method=method, path=path, params=params,
payload=payload, forceNewToken=True)
try:
raise Exception(response.json()['Error'])
except (JSONDecodeError, KeyError):
response.raise_for_status()
示例3: get_block_number
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def get_block_number(block_num, endpoint, get_tx_info=False):
url = endpoint
payload = json.dumps({
"jsonrpc": "2.0",
"method": "hmy_getBlockByNumber",
"params": [
str(hex(block_num)),
get_tx_info
],
"id": 1
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request('POST', url, headers=headers, data=payload, allow_redirects=False, timeout=30)
try:
returned = json.loads(response.content)["result"]
return returned
except Exception: # Catch all to not halt
num_bad_get_blocks.append({
'block-num': block_num,
'reason': f"Failed to json load block {block_num}. Content: {response.content}"
})
print(f"\n[!!!] Failed to json load block {block_num}. Content: {response.content}\n")
示例4: get_block_hash
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def get_block_hash(block_hash, endpoint, get_tx_info=False):
url = endpoint
payload = json.dumps({
"jsonrpc": "2.0",
"method": "hmy_getBlockByNumber",
"params": [
block_hash if block_hash.startswith('0x') else '0x' + block_hash,
get_tx_info
],
"id": 1
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request('POST', url, headers=headers, data=payload, allow_redirects=False, timeout=30)
try:
returned = json.loads(response.content)["result"]
return returned
except Exception: # Catch all to not halt
hash_bad_get_blocks.append({
'block-hash': block_hash,
'reason': f"Failed to json load block {block_hash}. Content: {response.content}"
})
print(f"\n[!!!] Failed to json load block {block_hash}. Content: {response.content}\n")
示例5: is_after_epoch
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def is_after_epoch(n):
url = args.hmy_endpoint_src
payload = """{
"jsonrpc": "2.0",
"method": "hmy_latestHeader",
"params": [ ],
"id": 1
}"""
headers = {
'Content-Type': 'application/json'
}
try:
response = requests.request('POST', url, headers=headers, data=payload, allow_redirects=False, timeout=3)
body = json.loads(response.content)
return int(body["result"]["epoch"]) > n
except (requests.ConnectionError, KeyError):
return False
示例6: interface_tests
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def interface_tests(method, url, data, record_time=True, **kwargs):
"""简单接口测试
:param method: 请求方法,比如:post、get
:param url: url地址
:param data: 传入的参数
:param record_time: 是否记录消耗时间
:param kwargs: 参考requests.post **kwargs
:return: 接口返回值
"""
start = time.time()
response = requests.request(method=method.upper(), url=url, data=data, **kwargs)
end = time.time()
if record_time:
return response.text, end - start
return response.text
示例7: _request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def _request(self, url, method, params=None, data=None, **kwargs):
url = "%s%s" % (self.api.base_url, url)
headers = self.get_auth_header()
headers.update(self.get_version_header())
headers.update(kwargs.pop("headers", {}))
try:
response = requests.request(method, url, params=params, data=data, headers=headers, **kwargs)
except Exception as e:
raise UnsplashError("Connection error: %s" % e)
try:
if not self._is_2xx(response.status_code):
if response.text == self.rate_limit_error:
raise UnsplashError(self.rate_limit_error)
else:
errors = response.json().get("errors")
raise UnsplashError(errors[0] if errors else None)
result = response.json()
except ValueError as e:
result = None
return result
示例8: on_attributes_update
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def on_attributes_update(self, content):
try:
for attribute_request in self.__attribute_updates:
if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
converted_data = attribute_request["converter"].convert(attribute_request, content)
response_queue = Queue(1)
request_dict = {"config": {**attribute_request,
**converted_data},
"request": request}
attribute_update_request_thread = Thread(target=self.__send_request,
args=(request_dict, response_queue, log),
daemon=True,
name="Attribute request to %s" % (converted_data["url"]))
attribute_update_request_thread.start()
attribute_update_request_thread.join()
if not response_queue.empty():
response = response_queue.get_nowait()
log.debug(response)
del response_queue
except Exception as e:
log.exception(e)
示例9: server_side_rpc_handler
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def server_side_rpc_handler(self, content):
try:
for rpc_request in self.__rpc_requests:
if fullmatch(rpc_request["deviceNameFilter"], content["device"]) and fullmatch(rpc_request["methodFilter"], content["data"]["method"]):
converted_data = rpc_request["converter"].convert(rpc_request, content)
response_queue = Queue(1)
request_dict = {"config": {**rpc_request,
**converted_data},
"request": request}
request_dict["config"].get("uplink_converter")
rpc_request_thread = Thread(target=self.__send_request,
args=(request_dict, response_queue, log),
daemon=True,
name="RPC request to %s" % (converted_data["url"]))
rpc_request_thread.start()
rpc_request_thread.join()
if not response_queue.empty():
response = response_queue.get_nowait()
log.debug(response)
self.__gateway.send_rpc_reply(device=content["device"], req_id=content["data"]["id"], content=response[2])
self.__gateway.send_rpc_reply(success_sent=True)
del response_queue
except Exception as e:
log.exception(e)
示例10: __fill_requests
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def __fill_requests(self):
log.debug(self.__config["mapping"])
for endpoint in self.__config["mapping"]:
try:
log.debug(endpoint)
converter = None
if endpoint["converter"]["type"] == "custom":
module = TBUtility.check_and_import(self.__connector_type, endpoint["converter"]["extension"])
if module is not None:
log.debug('Custom converter for url %s - found!', endpoint["url"])
converter = module(endpoint)
else:
log.error("\n\nCannot find extension module for %s url.\nPlease check your configuration.\n", endpoint["url"])
else:
converter = JsonRequestUplinkConverter(endpoint)
self.__requests_in_progress.append({"config": endpoint,
"converter": converter,
"next_time": time(),
"request": request})
except Exception as e:
log.exception(e)
示例11: on_attributes_update
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def on_attributes_update(self, content):
try:
for attribute_request in self.__attribute_updates:
if fullmatch(attribute_request["deviceNameFilter"], content["device"]) and \
fullmatch(attribute_request["attributeFilter"], list(content["data"].keys())[0]):
converted_data = attribute_request["downlink_converter"].convert(attribute_request, content)
response_queue = Queue(1)
request_dict = {"config": {**attribute_request,
**converted_data},
"request": regular_request}
with self._app.test_request_context():
attribute_update_request_thread = Thread(target=self.__send_request,
args=(request_dict, response_queue, log),
daemon=True,
name="Attribute request to %s" % (converted_data["url"]))
attribute_update_request_thread.start()
attribute_update_request_thread.join()
if not response_queue.empty():
response = response_queue.get_nowait()
log.debug(response)
del response_queue
except Exception as e:
log.exception(e)
示例12: make_api_call_all_pages
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def make_api_call_all_pages(conf, action, params = {}):
"""
A wrapper of make_api_call() to get all pages on a GET request
"""
start = 0
results = []
looping = True
params.update({'limit':conf['PAGINATION']})
while looping:
params.update({'start':start})
json = make_api_call(conf, action, params)
for r in json.get('data'):
results.append(r)
is_more = json.get('additional_data').get('pagination').get('more_items_in_collection')
if is_more:
start = json.get('additional_data').get('pagination').get('next_start')
else:
looping = False
return results
示例13: test_as_requests_kwargs
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def test_as_requests_kwargs(override, server, base_url, swagger_20, converter):
base_url = converter(base_url)
endpoint = Endpoint("/success", "GET", {}, swagger_20)
kwargs = {"endpoint": endpoint, "cookies": {"TOKEN": "secret"}}
if override:
case = Case(**kwargs)
data = case.as_requests_kwargs(base_url)
else:
case = Case(**kwargs)
endpoint.base_url = base_url
data = case.as_requests_kwargs()
assert data == {
"headers": None,
"json": None,
"method": "GET",
"params": None,
"cookies": {"TOKEN": "secret"},
"url": f"http://127.0.0.1:{server['port']}/api/success",
}
response = requests.request(**data)
assert response.status_code == 200
assert response.json() == {"success": True}
示例14: figshare_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def figshare_request(
endpoint=None, data=None, method='GET', url=None,
binary=False, error_level=logging.ERROR):
"""Perform a REST request against the figshare API."""
headers = {'Authorization': 'token ' + repository().get('token', '')}
if data is not None and not binary:
data = json.dumps(data)
response = requests.request(
method, url or _FIGSHARE_BASE_URL.format(endpoint=endpoint), headers=headers, data=data)
try:
response.raise_for_status()
try:
data = json.loads(response.content)
except ValueError:
data = response.content
except HTTPError as error:
logger.log(error_level, error)
raise error
return data
示例15: log_request_completion
# 需要导入模块: import requests [as 别名]
# 或者: from requests import request [as 别名]
def log_request_completion(self, response, request, start):
apireq = request.environ.get('ec2.request', None)
if apireq:
action = apireq.action
else:
action = None
ctxt = request.environ.get('ec2api.context', None)
delta = timeutils.utcnow() - start
seconds = delta.seconds
microseconds = delta.microseconds
LOG.info(
"%s.%ss %s %s %s %s %s [%s] %s %s",
seconds,
microseconds,
request.remote_addr,
request.method,
"%s%s" % (request.script_name, request.path_info),
action,
response.status_int,
request.user_agent,
request.content_type,
response.content_type,
context=ctxt)