本文整理汇总了Python中requests.sessions.Session方法的典型用法代码示例。如果您正苦于以下问题:Python sessions.Session方法的具体用法?Python sessions.Session怎么用?Python sessions.Session使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests.sessions
的用法示例。
在下文中一共展示了sessions.Session方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: requests_session
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def requests_session(*, auth: Optional[Any] = None, headers: Optional[Any] = None, **kwargs: Any) -> Session:
session = requests.Session()
if auth:
session.auth = auth
# setup SSL
cafile = config.get('ca')
if cafile:
session.verify = cafile
# set headers
if headers is None:
headers = dict()
headers.setdefault('User-Agent', USER_AGENT)
session.headers = headers
if kwargs:
session.__dict__.update(kwargs)
return session
示例2: get_discovery_doc
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def get_discovery_doc(environment, session=None):
"""Gets discovery doc based on environment specified.
:param environment: App environment, accepted values: 'sandbox','production','prod','e2e'
:param session: `requests.Session` object if a session is already being used, defaults to None
:return: Discovery doc response
:raises HTTPError: if response status != 200
"""
if environment.lower() in ['production', 'prod']:
discovery_url = DISCOVERY_URL['production']
else:
discovery_url = DISCOVERY_URL['sandbox']
response = requests.get(url=discovery_url, headers={'User-Agent': 'Mozilla/5.0'})
if response.status_code != 200:
raise AuthClientError(response)
return response.json()
示例3: from_requests_session
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def from_requests_session(cls, other):
"""Creates a `SynchronizedSession` from the provided `requests.Session`
object. Does not modify the original object, but does not perform a
deep copy either, so modifications to the returned
`SynchronizedSession` might affect the original session object as well,
and vice versa.
"""
# this is a moderate HACK:
# we use __getstate__() and __setstate__(), intended to help pickle
# sessions, to get all of the state of the provided session and add
# it to the new one, throwing away the adapters since we don't want
# those to be overwritten.
# the output of __getstate__() is supposed to be an opaque blob that
# you aren't really supposed to inspect or modify, so this relies on
# specifics of the implementation of requests.Session that are not
# guaranteed to be stable.
session_state = other.__getstate__()
if 'adapters' in session_state:
del session_state['adapters']
new_session = cls()
new_session.__setstate__(session_state)
return new_session
示例4: _web_request
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def _web_request(url, parameters):
"""
Perform HTTP GET request and return response.
Args:
url: Absolute URL
parameters: URL parameters
Returns:
Response as a string
"""
auth = (username, password)
with sessions.Session() as session:
response = session.request('GET', url, params=parameters, auth=auth,
verify=True)
if not response.ok:
response.raise_for_status()
return response.content.decode('utf-8')
示例5: __makeRequest
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def __makeRequest(self, url, method="GET", data=None, auth=None):
if auth is None and self.auth:
auth = self.auth
requestObj = Request(method=method, url=url, data=data, auth=auth)
prep_req = requestObj.prepare()
with sessions.Session() as session:
response = session.send(prep_req)
if response.status_code == 200:
if (response.content and hasattr(response.content, "decode")):
return response.content.decode("utf-8")
return response.content
if response.status_code == 401:
raise SplitwiseUnauthorizedException("Please check your token or consumer id and secret", response=response)
if response.status_code == 403:
raise SplitwiseNotAllowedException("You are not allowed to perform this operation", response=response)
if response.status_code == 400:
raise SplitwiseBadRequestException("Please check your request", response=response)
if response.status_code == 404:
raise SplitwiseNotFoundException("Required resource is not found", response)
raise SplitwiseException("Unknown error happened", response)
示例6: test_init
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def test_init(self):
api_key, base_url, api_version = TestApiClient.mock_client_params()
client = Client(api_key, base_url, api_version)
self.assertEqual(client.API_VERSION, api_version)
self.assertEqual(client.BASE_API_URI, base_url)
self.assertIsInstance(client.session, Session)
示例7: send_request
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def send_request(method, url, header, obj, body=None, session=None, oauth1_header=None):
"""Makes API request using requests library, raises `intuitlib.exceptions.AuthClientError` if request not successful and sets specified object attributes from API response if request successful
:param method: HTTP method type
:param url: request URL
:param header: request headers
:param obj: object to set the attributes to
:param body: request body, defaults to None
:param session: requests session, defaults to None
:param oauth1_header: OAuth1 auth header, defaults to None
:raises AuthClientError: In case response != 200
:return: requests object
"""
headers = ACCEPT_HEADER
header.update(headers)
if session is not None and isinstance(session, Session):
response = session.request(method, url, headers=header, data=body, auth=oauth1_header)
else:
response = requests.request(method, url, headers=header, data=body, auth=oauth1_header)
if response.status_code != 200:
raise AuthClientError(response)
if response.content:
set_attributes(obj, response.json())
return response
示例8: __init__
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def __init__(self, url, username, password, timeout):
super(OpenDaylightRestClient, self).__init__()
self.url = url
self.timeout = timeout
self.session = sessions.Session()
self.session.auth = (username, password)
示例9: __init__
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def __init__(self, url):
self.url = url
self.session = Session()
self.logger = logging.getLogger(__name__)
示例10: __init__
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def __init__(self, url, key, cert=True, reanalyze=True):
self.url = url
self.key = key
if cert and os.path.isfile(cert):
self.cert = cert
else:
self.cert = False
self.reanalyze = reanalyze
self.headers = self._prepare_headers()
self.session = sessions.Session()
self.session.headers = self.headers
self.session.verify = self.cert
示例11: create_session
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def create_session(self):
"""
如果接收到的要变参数中有session,且为Session对象,赋值给session变量, 否则创建一个
"""
if self.is_class:
self.session = getattr(self.func_im_self, 'session', None)
if not isinstance(self.session, Session):
session = Session()
setattr(self.func_im_self, 'session', session)
self.session = session
elif isinstance(self.func_return.get('session'), Session):
self.session = self.func_return.get('session')
else:
self.session = Session()
示例12: make_session
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def make_session():
return Session()
示例13: _prepare_session
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def _prepare_session(self):
self.session = Session()
if self.proxy_server_name is not None:
proxy_server = self.proxy_server_name
self._LOGGER.info("Using proxy server: " + proxy_server)
if self.proxy_server_port is not None:
proxy_server = proxy_server + ":" + self.proxy_server_port
self._LOGGER.info("Using proxy server port: " + self.proxy_server_port)
proxies = {'https': proxy_server}
self.session.proxies.update(proxies)
else:
self._LOGGER.info("No proxy server is in use")
self.session.mount("http://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
self.session.mount("https://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
示例14: _run_request
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def _run_request(self, request):
"""
Executes HTTP GET request with timeout using the endpoint defined upon client creation.
"""
session = Session()
session.mount("http://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
session.mount("https://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
result = session.get(self.endpoint + "?" + request, headers=self._get_custom_headers(), timeout=self.timeout)
result.raise_for_status()
return result
示例15: __init__
# 需要导入模块: from requests import sessions [as 别名]
# 或者: from requests.sessions import Session [as 别名]
def __init__(self, host, user_agent, api_key, api_secret, timeout=None):
self._host = host
self._session = session = Session()
self.timeout = None
session.auth = (api_key, api_secret) # Basic authentication.
session.headers.update({"User-Agent": user_agent})