本文整理汇总了Python中requests.Session方法的典型用法代码示例。如果您正苦于以下问题:Python requests.Session方法的具体用法?Python requests.Session怎么用?Python requests.Session使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.Session方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(self, url, mutual_auth, cert=None, verify='true', **kwargs):
self._logger = logging.getLogger("SPOT.INGEST.HDFS_client")
session = Session()
if verify == 'true':
self._logger.info('SSL verification enabled')
session.verify = True
if cert is not None:
self._logger.info('SSL Cert: ' + cert)
if ',' in cert:
session.cert = [path.strip() for path in cert.split(',')]
else:
session.cert = cert
elif verify == 'false':
session.verify = False
super(SecureKerberosClient, self).__init__(url, mutual_auth, session=session, **kwargs)
示例2: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(self, user_agent, token_url_template, platform):
self.user_agent = user_agent
self.token_url_template = token_url_template
self.platform = platform
self.session = requests.Session()
self.session.cookies = http.cookiejar.LWPCookieJar()
if not os.path.exists(COOKIE_FILE):
self.session.cookies.save(COOKIE_FILE)
self.session.cookies.load(COOKIE_FILE, ignore_discard=True)
self.session.headers = {"User-agent": user_agent}
if os.path.exists(SESSION_FILE):
self.load()
else:
self._state = {
'api_key': None,
'client_api_key': None,
'token': None,
'access_token': None,
'access_token_expiry': None
}
self.login()
示例3: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(self, **kwargs):
super(XueQiuClient, self).__init__()
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
'Host': 'xueqiu.com',
'Pragma': 'no-cache',
'Connection': 'keep-alive',
'Accept': '*/*',
'Accept-Encoding': 'gzip,deflate,sdch',
'Cache-Control': 'no-cache',
'Referer': 'http://xueqiu.com/P/ZH003694',
'X-Requested-With': 'XMLHttpRequest',
'Accept-Language': 'zh-CN,zh;q=0.8'
}
self.session = requests.Session()
self.session.headers.update(headers)
self.account_config = None
self.config.update({
"create_cubes_url": "https://xueqiu.com/cubes/create.json",
"get_token_url": "https://xueqiu.com/service/csrf",
"get_cubes_list": "https://xueqiu.com/v4/stock/portfolio/stocks.json",
"get_cubes_detail": "https://xueqiu.com/cubes/quote.json",
})
示例4: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(self, scheme='http', marker=None, timeout=None):
self.logger = logging.getLogger(__name__)
self.__session = requests.Session()
self.set_auth()
self.marker = marker
self.__session.headers.update({'X-Context-Marker': marker})
self.prom_url = self._get_prom_url()
self.port = self.prom_url.port
self.host = self.prom_url.hostname
self.scheme = scheme
if self.port:
self.base_url = "%s://%s:%s/api/" % (self.scheme, self.host,
self.port)
else:
# assume default port for scheme
self.base_url = "%s://%s/api/" % (self.scheme, self.host)
self.default_timeout = self._calc_timeout_tuple((20, 30), timeout)
示例5: connect
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def connect(self):
if self.session is None:
# Creating a session that can later be re-use to configure custom mechanisms
self.session = requests.Session()
# If we specified some retries, we provide a predefined retry-logic
if self.retries > 0:
adapter = HTTPAdapter(
max_retries=Retry(
total=self.retries,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
)
)
for prefix in "http://", "https://":
self.session.mount(prefix, adapter)
else:
raise TransportAlreadyConnected("Transport is already connected")
示例6: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(
self,
appid,
api_key,
mch_id,
sub_mch_id=None,
mch_cert=None,
mch_key=None,
timeout=None,
sandbox=False,
sub_appid=None,
):
self.appid = appid
self.sub_appid = sub_appid
self.api_key = api_key
self.mch_id = mch_id
self.sub_mch_id = sub_mch_id
self.mch_cert = mch_cert
self.mch_key = mch_key
self.timeout = timeout
self.sandbox = sandbox
self._sandbox_api_key = None
self._http = requests.Session()
示例7: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(
self, component_appid, component_appsecret, component_token, encoding_aes_key, session=None, auto_retry=True,
):
"""
:param component_appid: 第三方平台appid
:param component_appsecret: 第三方平台appsecret
:param component_token: 公众号消息校验Token
:param encoding_aes_key: 公众号消息加解密Key
"""
self._http = requests.Session()
self.component_appid = component_appid
self.component_appsecret = component_appsecret
self.expires_at = None
self.crypto = WeChatCrypto(component_token, encoding_aes_key, component_appid)
self.session = session or MemoryStorage()
self.auto_retry = auto_retry
示例8: requests_retry_session
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None,
):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
示例9: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __init__(
self,
url: str,
auth: Auth = None,
verify: Verify = True,
requests_session: requests.Session = None,
) -> None:
self.url = url
self.auth = auth
self.verify = verify
if requests_session is None:
self.session = requests.Session()
self.managed_session = True
else:
self.session = requests_session
self.managed_session = False
示例10: get_raw
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def get_raw(stocks) -> dict:
req = requests.Session()
req.get(SESSION_URL, proxies=get_proxies())
r = req.get(
STOCKINFO_URL.format(
stock_id=_join_stock_id(stocks),
time=int(time.time()) * 1000))
if sys.version_info < (3, 5):
try:
return r.json()
except ValueError:
return {'rtmessage': 'json decode error', 'rtcode': '5000'}
else:
try:
return r.json()
except json.decoder.JSONDecodeError:
return {'rtmessage': 'json decode error', 'rtcode': '5000'}
示例11: get_session
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def get_session(k8s_api_verify_tls):
global session
if session is None:
with open('/var/run/secrets/kubernetes.io/serviceaccount/token') as token_file:
token = token_file.read()
session = requests.Session()
session.headers = {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
'User-Agent': user_agent('Deis Controller', deis_version)
}
if k8s_api_verify_tls:
session.verify = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'
else:
session.verify = False
return session
示例12: router_login
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def router_login(base_url):
"""
Prompt for router username and password and attempt login.
Returns the username if successful or None.
"""
config = PdtoolsConfig.load()
session = requests.Session()
url_parts = urlparse(base_url)
for username, password in LoginGatherer(url_parts.netloc):
# Try to get a token for later use. Prior to 1.10, paradrop-daemon
# does not not support tokens.
_, token = send_router_login(base_url, username, password, session)
if token is not None:
config.addAccessToken(url_parts.netloc, username, token)
config.save()
return username
return None
示例13: signed_session
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def signed_session(self, session: requests.Session = None) -> requests.Session:
"""
Gets the signed session. This is called by the msrest package
:returns: Signed requests.Session object
"""
if not session:
session = requests.Session()
if not self._should_authorize(session):
session.headers.pop("Authorization", None)
else:
auth_token = self.get_access_token()
header = "{} {}".format("Bearer", auth_token)
session.headers["Authorization"] = header
return session
示例14: __login
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def __login(self):
'''
Login to the site if we're not logged in already. First try any
existing session from the stored cookie. If that fails we should
login again.
'''
self.__load_cookies()
if not self.__is_logged_in():
log('Logging in')
form_data = {
'userID': self.config.email,
'password': self.config.password
}
self.session = requests.Session()
# Get CSRF-token and add it to the form data.
form_data['__RequestVerificationToken'] = self.__get_token()
# Do the actual logging in.
self.session.post(LOGINPAGE + '?Returnurl=~%2F', data=form_data)
# Save the cookies to file.
self.__save_cookies()
else:
log('Already logged in')
示例15: download_image_requests_to_dir
# 需要导入模块: import requests [as 别名]
# 或者: from requests import Session [as 别名]
def download_image_requests_to_dir(img_url, dir_name):
dir_utils.clear_directory(f'{dir_utils.get_temp_med_dir()}/{dir_name}')
img_ext = img_url.rsplit('.', 1)[1]
s = requests.Session()
r = s.get(img_url)
if r.status_code == 200:
with open(f"{dir_utils.get_temp_med_dir()}/{dir_name}/_image.{img_ext}", 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
dprint(f"Downloaded image from: {img_url}")
else:
dprint(f"{r.status_code} Error! - {img_url}")
if img_ext == 'png':
dprint(f"Fixing image to force jpg conversion: {img_url}")
img_fix = Image.open(f"{dir_utils.get_temp_med_dir()}/{dir_name}/_image.{img_ext}")
img_fix.convert('RGB').save(f"{dir_utils.get_temp_med_dir()}/{dir_name}/_image.jpg")
dir_utils.remove_file("_image.png", f'{dir_utils.get_temp_med_dir()}/{dir_name}')
dprint(f"Downloaded image from: {img_url}")