本文整理汇总了Python中requests.session方法的典型用法代码示例。如果您正苦于以下问题:Python requests.session方法的具体用法?Python requests.session怎么用?Python requests.session使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.session方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_access_rules
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def fetch_access_rules(session, page_num=1, zone_id=None, per_page=50):
"""
Fetch current access rules from the CloudFlare API
"""
# If zone_id, only apply rule to current zone/domain
params = {'page': page_num, 'per_page': per_page}
if zone_id:
r = session.get('https://api.cloudflare.com/client/v4/zones/{}'
'/firewall/access_rules/rules'.format(
zone_id), params=params)
else:
r = session.get('https://api.cloudflare.com/client/v4/user'
'/firewall/access_rules/rules', params=params)
r.raise_for_status()
res = r.json()
if not res['success']:
raise CloudFlareAPIError(res['errors'])
else:
return res
示例2: remove_access_rule
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def remove_access_rule(session, rule_id, zone_id=None):
"""
Remove an existing access rule via the CloudFlare API
"""
if zone_id:
r = session.delete('https://api.cloudflare.com/client/v4/zones/{}'
'/firewall/access_rules/rules/{}'.format(
zone_id, rule_id))
else:
# Apply rule across all zones
r = session.delete('https://api.cloudflare.com/client/v4/user'
'/firewall/access_rules/rules/{}'.format(
rule_id))
r.raise_for_status()
res = r.json()
if not res['success']:
raise CloudFlareAPIError(res['errors'])
示例3: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def __init__(self, product_link, domain):
'''
(str, str) -> eBae
Given a link to an eBay product <product_link> and a catch-all domain
address <domain>, a random email address is generated and an eBae
object is returned.
REQ: domain is a catch-all domain
REQ: product_link is a link to a product listed on eBay
'''
self.s = requests.session()
self.product_link = product_link
self.s.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
}
self.proxy_list = read_from_txt("proxies.txt")
self.email = gen_email(domain)
示例4: yt
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def yt(query):
with requests.session() as s:
isi = []
if query == "":
query = "S1B tanysyz"
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
if 'watch?v' in a['href']:
b = a['href'].replace('watch?v=', '')
isi += ['youtu.be' + b]
return isi
示例5: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def __init__(self, swift_config, **kwargs):
self.auth_url = swift_config['swift_auth_url']
self.user_id = swift_config['swift_user_id']
self.project_id = swift_config['swift_project_id']
self.password = swift_config['swift_password']
self.region = swift_config['swift_region']
self.endpoint = None
if 'token' in swift_config:
self.token = swift_config['token']
self.endpoint = swift_config['endpoint']
else:
self.token = self.generate_swift_token()
swift_config['token'] = self.token
swift_config['endpoint'] = self.endpoint
self.session = requests.session()
self.session.headers.update({'X-Auth-Token': self.token})
adapter = requests.adapters.HTTPAdapter(pool_maxsize=64, max_retries=3)
self.session.mount('http://', adapter)
self.session.mount('https://', adapter)
示例6: put_object
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def put_object(self, container_name, key, data):
"""
Put an object in Swift. Override the object if the key already exists.
:param key: key of the object.
:param data: data of the object
:type data: str/bytes
:return: None
"""
url = '/'.join([self.endpoint, container_name, key])
try:
res = self.session.put(url, data=data)
status = 'OK' if res.status_code == 201 else 'Error'
try:
logger.debug('PUT Object {} - Size: {} - {}'.format(key, sizeof_fmt(len(data)), status))
except Exception:
logger.debug('PUT Object {} - {}'.format(key, status))
except Exception as e:
print(e)
示例7: head_object
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def head_object(self, container_name, key):
"""
Head object from Swift with a key. Throws StorageNoSuchKeyError if the given key does not exist.
:param key: key of the object
:return: Data of the object
:rtype: str/bytes
"""
url = '/'.join([self.endpoint, container_name, key])
try:
res = self.session.head(url)
if res.status_code == 200:
return res.headers
elif res.status_code == 404:
raise StorageNoSuchKeyError(container_name, key)
else:
raise Exception('{} - {}'.format(res.status_code, key))
except Exception as e:
raise StorageNoSuchKeyError(container_name, key)
示例8: bucket_exists
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def bucket_exists(self, container_name):
"""
Head container from Swift with a name. Throws StorageNoSuchKeyError if the given container does not exist.
:param container_name: name of the container
:return: Data of the bucket
:rtype: str/bytes
"""
url = '/'.join([self.endpoint, container_name])
try:
res = self.session.head(url)
if res.status_code == 204:
return res.headers
elif res.status_code == 404:
raise StorageNoSuchKeyError(container_name, '')
else:
raise Exception('{} - {}'.format(res.status_code))
except Exception as e:
raise StorageNoSuchKeyError(container_name, '')
示例9: list_objects
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def list_objects(self, container_name, prefix=''):
"""
Lists the objects in a bucket. Throws StorageNoSuchKeyError if the given bucket does not exist.
:param key: key of the object
:return: Data of the object
:rtype: str/bytes
"""
if prefix:
url = '/'.join([self.endpoint, container_name, '?format=json&prefix='+prefix])
else:
url = '/'.join([self.endpoint, container_name, '?format=json'])
try:
res = self.session.get(url)
objects = res.json()
# TODO: Adapt to Key and Size
return objects
except Exception as e:
raise e
示例10: dojo_get_address
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def dojo_get_address(addr, at):
# Request details about a collection of HD accounts and/or loose addresses and/or public keys.
# Takes arguments:
# addr: address or list of addresses
# at: authentication token
onion_address = dojo_get_settings()["onion"]
url = "http://" + onion_address + "/v2/address/" + addr + "/info?at=" + at
session = requests.session()
session.proxies = {
"http": "socks5h://127.0.0.1:9150",
"https": "socks5h://127.0.0.1:9150",
}
try:
auth_response = session.get(url)
except requests.exceptions.ConnectionError:
auth_response = {"status": "error", "error": "Connection Error"}
return auth_response
示例11: dojo_get_hd
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def dojo_get_hd(xpub, at):
# Request details about an HD account. If account does not exist, it must be created.
# https://github.com/Samourai-Wallet/samourai-dojo/blob/master/doc/GET_xpub.md
onion_address = dojo_get_settings()["onion"]
url = "http://" + onion_address + "/v2/xpub/"
session = requests.session()
session.proxies = {
"http": "socks5h://127.0.0.1:9150",
"https": "socks5h://127.0.0.1:9150",
}
try:
url = url + xpub + "?at=" + at
auth_response = session.get(url)
except requests.exceptions.ConnectionError:
auth_response = {"status": "error", "error": "Connection Error"}
return auth_response
示例12: youtube_session
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def youtube_session() -> Iterator[requests.Session]:
"""This context opens a requests session and loads the youtube cookies file."""
session = requests.session()
try:
with open(
os.path.join(settings.BASE_DIR, "config/youtube_cookies.pickle"), "rb"
) as f:
session.cookies.update(pickle.load(f))
except FileNotFoundError:
pass
headers = {
"User-Agent": youtube_dl.utils.random_user_agent(),
}
session.headers.update(headers)
yield session
with open(
os.path.join(settings.BASE_DIR, "config/youtube_cookies.pickle"), "wb"
) as f:
pickle.dump(session.cookies, f)
示例13: get_search_suggestions
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def get_search_suggestions(query: str) -> List[str]:
"""Returns a list of suggestions for the given query from Youtube."""
with youtube_session() as session:
params = {
"client": "youtube",
"q": query[:100], # queries longer than 100 characters are not accepted
"xhr": "t", # this makes the response be a json file
}
response = session.get(
"https://clients1.google.com/complete/search", params=params
)
suggestions = json.loads(response.text)
# first entry is the query, the second one contains the suggestions
suggestions = suggestions[1]
# suggestions are given as tuples
# extract the string and skip the query if it occurs identically
suggestions = [entry[0] for entry in suggestions if entry[0] != query]
return suggestions
示例14: upload_doc
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def upload_doc(session, section_id, data_path, doc):
doc_path = get_doc_path(data_path, doc)
print('Processing %s%s (%s)' % (doc.location, doc.title, doc.guid))
with ZipFile(doc_path) as zip_file:
html_content, src_file_names = clean_html(zip_file.read('index.html'), doc)
if len(src_file_names) > 5:
print('Upload may failed if images more than 5')
data_send = {
'Presentation': (None, html_content, mimetypes.guess_type('index.html')[0])
}
for name in src_file_names:
data_send[name] = (None, zip_file.read('index_files/' + name), mimetypes.guess_type(name)[0])
resp = session.post(API_BASE + '/sections/%s/pages' % section_id, files=data_send)
resp.raise_for_status()
示例15: _request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import session [as 别名]
def _request(self, url, method=None, extra_params=None):
params = dict()
if extra_params:
params.update(extra_params)
headers = consts.HEADERS
if 'fm.baidu.com' in url:
headers['Host'] = "fm.baidu.com"
elif 'passport.baidu.com' in url:
headers['Host'] = "passport.baidu.com"
else:
headers['Host'] = ".baidu.com"
self._params_utf8(params)
if method and method.lower() == 'post':
response = self.session.post(url, data=params, verify=True, headers=headers)
else:
if '?' in url:
url = url + urlencode(params)
else:
url = url + '?' + urlencode(params)
response = self.session.get(url, verify=False, headers=headers)
return response