本文整理汇总了Python中requests.Session.close方法的典型用法代码示例。如果您正苦于以下问题:Python Session.close方法的具体用法?Python Session.close怎么用?Python Session.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests.Session
的用法示例。
在下文中一共展示了Session.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_http_request
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def get_http_request(url, payload, method='POST', headers=None, use_proxy=False, use_proxy_auth=False, trust_env=True):
try:
session = Session()
session.trust_env = trust_env
session.proxies = Util.get_proxies() if use_proxy else None
session.auth = Util.get_proxy_auth() if use_proxy_auth else None
request = Request(
'POST' if method not in ('GET', 'POST') else method,
url,
data=payload if method == 'POST' else None,
params=payload if method == 'GET' else None,
headers=headers
)
prepped = request.prepare()
response = session.send(
prepped,
timeout=app.config['HTTP_REQUESTS_TIMEOUT']
)
session.close()
except Exception, e:
response = Response()
response.raise_for_status()
return response, 'Error al realizar la consulta - Motivo: {}'.format(e.message)
示例2: hit_example_com
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def hit_example_com(self):
try:
start_time = time()
session = Session()
http_adapter = HTTPAdapter(max_retries=0)
session.mount('http://', http_adapter)
session.mount('https://', http_adapter)
session.get("http://www.example.com", timeout=30)
# # print("Doing a task that is not a request...")
# login = Login()
# r = login.sw_valid_login(GC.USERNAME, GC.PASSWORD, "http://www.sowatest.com")
stats_latency['latency'].append(time() - start_time)
events.request_success.fire(request_type="Transaction", name="hit_sowatest", response_time=time() - start_time, response_length=0)
session.close()
# # Assert Section
# assert r.status_code == 200
# assert "Access Denied" in str(html.fromstring(r.text).xpath("//title/text()"))
# assert '<div id="blockedBanner">' in r.text
except Exception, e:
"""
* *request_type*: Request type method used
* *name*: Path to the URL that was called (or override name if it was used in the call to the client)
* *response_time*: Time in milliseconds until exception was thrown
* *exception*: Exception instance that was thrown
"""
events.request_failure.fire(request_type="Transaction", name="hit_sowatest", response_time=time() - start_time, exception=e)
示例3: OneM2MHttpTx
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class OneM2MHttpTx(IoTTx):
"""Implementation of HTTP OneM2M Tx channel"""
def __init__(self, encoder, decoder):
super(OneM2MHttpTx, self).__init__(encoder, decoder)
self.session = None
def _start(self):
self.session = Session()
def _stop(self):
if self.session:
self.session.close()
self.session = None
def send(self, jsonprimitive):
try:
message = self.encoder.encode(jsonprimitive)
except IoTDataEncodeError as e:
return None
rsp_message = self.session.send(message)
rsp_primitive = None
try:
rsp_primitive = self.decoder.decode(rsp_message)
except IoTDataDecodeError as e:
return None
return rsp_primitive
示例4: send_message
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def send_message(self, request):
"""Transport the message to the server and return the response.
:param request: The JSON-RPC request string.
:return: The response (a string for requests, None for notifications).
"""
# Prepare the session
session = Session()
session_request = Request(method='POST', url=self.endpoint, \
headers=self.headers, data=request, **self.requests_kwargs)
prepared_request = session.prepare_request(session_request)
prepared_request.headers = dict(list(dict(
prepared_request.headers).items()) + list(self.headers.items()))
# Log the request
self.log_request(request, {'http_headers': prepared_request.headers})
# Send the message
try:
response = session.send(prepared_request)
except RequestException:
session.close()
raise
session.close()
# Log the response
self.log_response(response.text, {'http_code': response.status_code, \
'http_reason': response.reason, 'http_headers': response.headers})
return response.text
示例5: test_close
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def test_close(self):
cache = mock.Mock(spec=DictCache)
sess = Session()
sess.mount('http://', CacheControlAdapter(cache))
sess.close()
assert cache.close.called
示例6: __init__
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class PluggitHandler:
"""
handler is the global network handler for Pluggit. It routes all network
requests through it in order to respect Reddit API rules. It keeps all
OAuth requests separate as they are based on a per-user_agent rate-limit.
"""
def __init__(self, debug = False):
# Create logger
self.logger = logging.getLogger('PluggitHandler')
self.logger.setLevel(logging.INFO)
if debug:
self.logger.setLevel(logging.DEBUG)
# Create dict { bearer: last_request_time }
self.oauth_dict = {}
# Required by PRAW
self.session = Session()
self.lock = Lock()
def __del__(self):
if not self.session == None:
self.session.close()
def request(self, request, proxies, timeout, verify, **kwargs):
# Evict oauth_session if more than 1hr old
self.oauth_dict = { key:value for key, value in self.oauth_dict.items() if value < (time() + (60 * 60)) }
# Get current oauth_session
oauth_session = None
if 'Authorization' in request.headers:
payload = request.headers['Authorization'].split(' ')
if payload[0] == 'bearer':
oauth_session = payload[1]
if not oauth_session == None:
# Previously made a request
if oauth_session in self.oauth_dict:
# Lock to prevent multiple threads requesting from same OAUTH session
with self.lock:
now = time()
wait_time = self.oauth_dict[oauth_session] + 2 - now
if wait_time > 0:
self.logger.debug(' SESSION: ' + oauth_session + ' SLEEPING: ' + str(wait_time))
now += wait_time
sleep(wait_time)
self.oauth_dict[oauth_session] = now
else:
self.oauth_dict[oauth_session] = time()
return self.session.send(request,
proxies = proxies,
timeout = timeout,
allow_redirects = False, verify = verify)
示例7: __init__
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class Flowdock:
"""Simple wrapper for Flowdock REST API."""
API_URL = "https://api.flowdock.com"
def __init__(self, api_key, debug=False, print_function=None):
"""Initialize Flowdock API wrapper.
@param debug Print debug info if True
@param print_function Use this function to print debug info. By default
use python builtin print. Mainly for using click.echo without requiring
click as dependency.
"""
self.session = Session()
# requests accepts http basic auth as tuple (user, pass), however,
# Flowdoc uses only api key as username without password
self.session.auth = (api_key, None)
self.debug = debug
self.print = print_function if print_function else print
def get_organizations(self):
"""Get list of organizations this user has access to"""
url = "{}/organizations".format(self.API_URL)
if self.debug:
self.print("Sending GET request to URL {}".format(url))
r = self.session.get(url)
r.raise_for_status()
return r.json()
def find_user_orgs(self, email):
"""Find organizations this user belongs to"""
orgs = self.get_organizations()
return [org for org in orgs if Flowdock.user_in_org(email, org)]
@staticmethod
def user_in_org(email, org):
"""Chek if user is part of organization"""
for user in org['users']:
if user['email'] == email:
return True
return False
def delete_user_from_org(self, user, org):
url = "{}/organizations/{}/users/{}".format(self.API_URL,
org['parameterized_name'],
user['id'])
if self.debug:
self.print("Sending DELETE request to url {}".format(url))
r = self.session.delete(url)
r.raise_for_status()
def close(self):
self.session.close()
示例8: TheSubDBProvider
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class TheSubDBProvider(Provider):
"""TheSubDB Provider."""
languages = {Language.fromthesubdb(l) for l in language_converters['thesubdb'].codes}
required_hash = 'thesubdb'
server_url = 'http://api.thesubdb.com/'
subtitle_class = TheSubDBSubtitle
def __init__(self):
self.session = None
def initialize(self):
self.session = Session()
self.session.headers['User-Agent'] = ('SubDB/1.0 (subliminal/%s; https://github.com/Diaoul/subliminal)' %
__short_version__)
def terminate(self):
self.session.close()
def query(self, hash):
# make the query
params = {'action': 'search', 'hash': hash}
logger.info('Searching subtitles %r', params)
r = self.session.get(self.server_url, params=params, timeout=10)
# handle subtitles not found and errors
if r.status_code == 404:
logger.debug('No subtitles found')
return []
r.raise_for_status()
# loop over languages
subtitles = []
for language_code in r.text.split(','):
language = Language.fromthesubdb(language_code)
subtitle = self.subtitle_class(language, hash)
logger.debug('Found subtitle %r', subtitle)
subtitles.append(subtitle)
return subtitles
def list_subtitles(self, video, languages):
return [s for s in self.query(video.hashes['thesubdb']) if s.language in languages]
def download_subtitle(self, subtitle):
logger.info('Downloading subtitle %r', subtitle)
params = {'action': 'download', 'hash': subtitle.hash, 'language': subtitle.language.alpha2}
r = self.session.get(self.server_url, params=params, timeout=10)
r.raise_for_status()
subtitle.content = fix_line_ending(r.content)
示例9: getRates
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def getRates():
result = None
s = Session()
try:
resp = s.get(BASE_URL+LATEST_RATES, params={'app_id': APP_ID})
raw_rates_json = json.loads(resp.text)
result = raw_rates_json
except Exception as e:
result = None
finally:
s.close()
return result
示例10: getCurrencys
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def getCurrencys():
result = None
s = Session()
try:
resp = s.get(BASE_URL+CURRENCIES, params={'app_id': APP_ID})
currencys = json.loads(resp.text)
result = currencys
except Exception as e:
result = None
finally:
s.close()
return result
示例11: NapiProjektProvider
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class NapiProjektProvider(Provider):
"""NapiProjekt Provider."""
languages = {Language.fromalpha2(l) for l in ['pl']}
required_hash = 'napiprojekt'
server_url = 'http://napiprojekt.pl/unit_napisy/dl.php'
subtitle_class = NapiProjektSubtitle
def __init__(self):
self.session = None
def initialize(self):
self.session = Session()
self.session.headers['User-Agent'] = 'Subliminal/%s' % __short_version__
def terminate(self):
self.session.close()
def query(self, language, hash):
params = {
'v': 'dreambox',
'kolejka': 'false',
'nick': '',
'pass': '',
'napios': 'Linux',
'l': language.alpha2.upper(),
'f': hash,
't': get_subhash(hash)}
logger.info('Searching subtitle %r', params)
r = self.session.get(self.server_url, params=params, timeout=10)
r.raise_for_status()
# handle subtitles not found and errors
if r.content[:4] == b'NPc0':
logger.debug('No subtitles found')
return None
subtitle = self.subtitle_class(language, hash)
subtitle.content = r.content
logger.debug('Found subtitle %r', subtitle)
return subtitle
def list_subtitles(self, video, languages):
return [s for s in [self.query(l, video.hashes['napiprojekt']) for l in languages] if s is not None]
def download_subtitle(self, subtitle):
# there is no download step, content is already filled from listing subtitles
pass
示例12: TheSubDBProvider
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class TheSubDBProvider(Provider):
languages = {Language.fromthesubdb(l) for l in language_converters["thesubdb"].codes}
required_hash = "thesubdb"
server_url = "http://api.thesubdb.com/"
def initialize(self):
self.session = Session()
self.session.headers = {
"User-Agent": "SubDB/1.0 (subliminal/%s; https://github.com/Diaoul/subliminal)" % get_version(__version__)
}
def terminate(self):
self.session.close()
def query(self, hash):
# make the query
params = {"action": "search", "hash": hash}
logger.info("Searching subtitles %r", params)
r = self.session.get(self.server_url, params=params, timeout=10)
# handle subtitles not found and errors
if r.status_code == 404:
logger.debug("No subtitles found")
return []
r.raise_for_status()
# loop over languages
subtitles = []
for language_code in r.text.split(","):
language = Language.fromthesubdb(language_code)
subtitle = TheSubDBSubtitle(language, hash)
logger.debug("Found subtitle %r", subtitle)
subtitles.append(subtitle)
return subtitles
def list_subtitles(self, video, languages):
return [s for s in self.query(video.hashes["thesubdb"]) if s.language in languages]
def download_subtitle(self, subtitle):
logger.info("Downloading subtitle %r", subtitle)
params = {"action": "download", "hash": subtitle.hash, "language": subtitle.language.alpha2}
r = self.session.get(self.server_url, params=params, timeout=10)
r.raise_for_status()
subtitle.content = fix_line_ending(r.content)
示例13: ShooterProvider
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class ShooterProvider(Provider):
languages = {Language.fromalpha2(l) for l in ["zh"]}
required_hash = "shooter"
def initialize(self):
self.session = Session()
self.session.headers = {"User-Agent": "SPlayer Build 2437"}
def terminate(self):
self.session.close()
def query(self, hash):
# shooter has many DNS mirrors, e.g. splayer[1-9], but one is enough
params = {"pathinfo": "temp", "format": "json", "filehash": hash}
logger.info("Searching subtitles %r", params)
r = self.session.get("https://www.shooter.cn/api/subapi.php", params=params, timeout=10)
r.raise_for_status()
# loop over, server always returns found or not
subtitles = []
try:
for it in r.json():
# It normally contains one File, but can contain multiple
link = it["Files"][0]["Link"]
subtype = it["Files"][0]["Ext"]
subtitle = ShooterSubtitle(Language.fromalpha2("zh"), hash, link, subtype)
logger.debug("Found subtitle %r", subtitle)
subtitles.append(subtitle)
return subtitles
except:
logger.debug("No subtitle found")
return []
def list_subtitles(self, video, languages):
return [s for s in self.query(video.hashes["shooter"]) if s.language in languages]
def download_subtitle(self, subtitle):
logger.info("Download subtitle %r", subtitle.link)
r = self.session.get(subtitle.link, params=None, timeout=10)
r.raise_for_status()
subtitle.content = fix_line_ending(r.content)
示例14: ShooterProvider
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
class ShooterProvider(Provider):
"""Shooter Provider."""
languages = {Language(l) for l in ['eng', 'zho']}
server_url = 'https://www.shooter.cn/api/subapi.php'
subtitle_class = ShooterSubtitle
def __init__(self):
self.session = None
def initialize(self):
self.session = Session()
self.session.headers['User-Agent'] = 'Subliminal/%s' % __short_version__
def terminate(self):
self.session.close()
def query(self, language, filename, hash=None):
# query the server
params = {'filehash': hash, 'pathinfo': os.path.realpath(filename), 'format': 'json', 'lang': language.shooter}
logger.debug('Searching subtitles %r', params)
r = self.session.post(self.server_url, params=params, timeout=10)
r.raise_for_status()
# handle subtitles not found
if r.content == b'\xff':
logger.debug('No subtitles found')
return []
# parse the subtitles
results = json.loads(r.text)
subtitles = [self.subtitle_class(language, hash, t['Link']) for s in results for t in s['Files']]
return subtitles
def list_subtitles(self, video, languages):
return [s for l in languages for s in self.query(l, video.name, video.hashes.get('shooter'))]
def download_subtitle(self, subtitle):
logger.info('Downloading subtitle %r', subtitle)
r = self.session.get(subtitle.download_link, timeout=10)
r.raise_for_status()
subtitle.content = fix_line_ending(r.content)
示例15: try_request
# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import close [as 别名]
def try_request(self, request):
"""Place a secure request and get back an object of type T.
Args:
request: Result object of the request
Returns:
result: request response
"""
timestamp = int(time())
hash = create_secure_hash(timestamp, self.token)
request.auth = (self.userId, hash)
request.headers.update({'Timestamp': str(timestamp)})
request.url = self.client + request.url
try:
session = Session()
response = session.send(request.prepare())
session.close()
return response.json()
except:
exception('Failed to make REST request to {0}'.format(request.url))
return { 'success': False }