def _make_request(self, method, function_name, task_name, body=None):
uri_path = self._build_uri_path(function_name, task_name)
headers = self._build_aws_sigv4_headers(method, uri_path, body)
url = _ENDPOINT + uri_path
request = Request(
method,
url,
headers=headers,
json=body).prepare()
logger.debug('Invoking {} on URL {} with headers={}, body={}'.format(
request.method,
request.url,
json.dumps(dict(request.headers)),
request.body))
response = Session().send(request, timeout=_TIMEOUT_SECONDS)
return response
python类request()的实例源码
def prepare_request(*args, **kwargs):
r = requests.Request(*args, **kwargs)
s = requests.Session()
return s.prepare_request(r)
def generate_url(self, node_id, definition_name, escape=False):
"""
Returns the url for retrieving the specified node from the Graph API
given the node type definition.
"""
url, params = self._prepare_node_request(node_id, definition_name)
if not escape:
return '{}?{}'.format(url, '&'.join(['{}={}'.format(k, v) for k, v in params.items()]))
else:
return requests.Request('GET', url, params=params).prepare().url
def start_txn(self, txn_name=None):
'''
Request new transaction from repository, init new Transaction,
store in self.txns
Args:
txn_name (str): human name for transaction
Return:
(Transaction): returns intance of newly created transaction
'''
# if no name provided, create one
if not txn_name:
txn_name = uuid.uuid4().hex
# request new transaction
txn_response = self.api.http_request('POST','%s/fcr:tx' % self.root, data=None, headers=None)
# if 201, transaction was created
if txn_response.status_code == 201:
txn_uri = txn_response.headers['Location']
logger.debug("spawning transaction: %s" % txn_uri)
# init new Transaction, and pass Expires header
txn = Transaction(
self, # pass the repository
txn_name,
txn_uri,
expires = txn_response.headers['Expires'])
# append to self
self.txns[txn_name] = txn
# return
return txn
def response(
method='GET',
host='http://example.com',
url='/',
code=200,
elapsed=1.0):
req = requests.Request(method, host + url)
resp = requests.Response()
resp.request = req.prepare()
resp.status_code = code
resp.elapsed = timedelta(seconds=elapsed)
return resp
def test_configure():
session = requests.Session()
talisker.requests.configure(session)
req = requests.Request('GET', 'http://localhost')
with talisker.request_id.context('XXX'):
prepared = session.prepare_request(req)
assert prepared.headers['X-Request-Id'] == 'XXX'
def forward_req(context, action, b_headers, b_url, b_body):
s = Session()
req = Request(action, b_url,
data=b_body,
headers=b_headers)
prepped = req.prepare()
# do something with prepped.body
# do something with prepped.headers
resp = s.send(prepped,
timeout=60)
return resp
def http_request(self, method, path, data=None, params=None):
""" Wraps HTTP calls to ThrestStack API """
s = Session()
url = urljoin(self.BASE_URL, path)
headers = {"Authorization": self.api_key}
if self.org_id:
headers[self.org_id_header] = self.org_id
req = Request(
method,
url,
headers=headers,
data=data,
params=params
)
prepped = req.prepare()
resp = s.send(prepped, timeout=self.timeout)
if resp.status_code == 429:
raise errors.APIRateLimitError("Threat Stack API rate limit exceeded")
else:
return self.handle_response(resp)
def _query(self, *args, **kwargs):
req = requests.Request(*args, **kwargs)
res = self.client.send(req.prepare())
if res.status_code != 200:
raise MartException(res)
if res.text.startswith('Query ERROR:'):
raise MartException(res.text)
return res.text
def _request(self, endpoint, params):
params["initial_app_strings"] = "geORNtsZe5I4lRGjG9GZiA"
if self.custom_sessionid:
params["custom_sessionid"] = self.custom_sessionid
else:
params["custom_sessionid"] = ""
req = Request('POST', url=BASE_URL + endpoint, data=params).prepare()
log.debug("invoking carwings API: %s" % req.url)
log.debug("params: %s" % json.dumps(params, sort_keys=True, indent=3, separators=(',', ': ')))
try:
sess = requests.Session()
response = sess.send(req)
log.debug('Response HTTP Status Code: {status_code}'.format(
status_code=response.status_code))
log.debug('Response HTTP Response Body: {content}'.format(
content=response.content))
except RequestException:
log.warning('HTTP Request failed')
j = json.loads(response.content)
if "message" in j and j["message"] == "INVALID PARAMS":
log.error("carwings error %s: %s" % (j["message"], j["status"]) )
raise CarwingsError("INVALID PARAMS")
if "ErrorMessage" in j:
log.error("carwings error %s: %s" % (j["ErrorCode"], j["ErrorMessage"]) )
raise CarwingsError
return j