本文整理匯總了Python中requests.sessions.Session.get方法的典型用法代碼示例。如果您正苦於以下問題:Python Session.get方法的具體用法?Python Session.get怎麽用?Python Session.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類requests.sessions.Session
的用法示例。
在下文中一共展示了Session.get方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_session_persistent_params
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
def test_session_persistent_params(self):
params = {'a': 'a_test'}
s = Session()
s.params = params
# Make 2 requests from Session object, should send header both times
r1 = s.get(httpbin('get'))
assert params['a'] in r1.content
params2 = {'b': 'b_test'}
r2 = s.get(httpbin('get'), params=params2)
assert params['a'] in r2.content
assert params2['b'] in r2.content
params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}
r3 = s.get(httpbin('get'), params=params3)
assert not params['a'] in r3.content
assert params3['b'] in r3.content
assert params3['c'] in r3.content
示例2: test_session_persistent_headers
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
def test_session_persistent_headers(self):
heads = {'User-agent': 'Mozilla/5.0'}
s = Session()
s.headers = heads
# Make 2 requests from Session object, should send header both times
r1 = s.get(httpbin('user-agent'))
assert heads['User-agent'] in r1.content
r2 = s.get(httpbin('user-agent'))
assert heads['User-agent'] in r2.content
self.assertEqual(r2.status_code, 200)
示例3: get
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
def get(self, url, **kwargs):
return Session.get(
self,
self._get_resource_uri(url),
**self._set_default_timeout(
**kwargs
)
)
示例4: fetch_data
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
def fetch_data(dl_type=None, **kwargs):
"""
Fetch Receipts, Expenditures, and Committees.
dl_type is one of those three choices.
kwargs depend on the choice.
Receipts and Expenditures need start_date and end_date for search.
Committees need a name_start kwarg to pass into the search.
Seems like the maximum that you can get is about 250,000 records at a time.
"""
s = Session()
post_data = {
'__EVENTTARGET': 'ctl00$ContentPlaceHolder1$btnText',
'ctl00$pnlMenu_CollapsiblePanelExtender_ClientState': 'true',
'ctl00$AccordionStateBoardMenu_AccordionExtender_ClientState': '0',
'ctl00$mtbSearch': '',
'ctl00$AccordionPaneStateBoardMenu_content$AccordionMainContent_AccordionExtender_ClientState': '-1',
'hiddenInputToUpdateATBuffer_CommonToolkitScripts': '1',
'__EVENTARGUMENT': '',
'__VIEWSTATEGENERATOR': 'E8D1F59A'
}
if dl_type == 'Receipts':
CONT_GET_PARAMS['RcvDate'] = kwargs['start_date']
CONT_GET_PARAMS['RcvDateThru'] = kwargs['end_date']
url = '%s/DownloadList.aspx?%s' % (BASE_URL, urlencode(CONT_GET_PARAMS))
elif dl_type == 'Committees':
COMM_GET_PARAMS['Name'] = kwargs['name_start']
url = '%s/DownloadList.aspx?%s' % (BASE_URL, urlencode(COMM_GET_PARAMS))
elif dl_type == 'Expenditures':
EXP_GET_PARAMS['ExpendedDate'] = kwargs['start_date']
EXP_GET_PARAMS['ExpendedDateThru'] = kwargs['end_date']
url = '%s/DownloadList.aspx?%s' % (BASE_URL, urlencode(EXP_GET_PARAMS))
elif dl_type == 'Candidates':
url = 'http://www.elections.state.il.us/ElectionInformation/CandDataFile.aspx?id=%s' % kwargs['election_id']
g = s.get(url)
if 'Unexpected errors occurred trying to populate page' in g.content:
return None
soup = BeautifulSoup(g.content)
view_state = soup.find('input', attrs={'id': '__VIEWSTATE'}).get('value')
event_val = soup.find('input', attrs={'id': '__EVENTVALIDATION'}).get('value')
post_data['__VIEWSTATE'] = view_state
post_data['__EVENTVALIDATION'] = event_val
dl_page = s.post(url, data=post_data)
if dl_page.status_code == 200:
return dl_page.content
else:
return None
示例5: Api
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
class Api(object):
API_URL = 'http://192.168.33.10' # todo: add to config
API_VERSION = 'v1'
def __init__(self, device_key):
self.base_url = '{0}/{1}/'.format(self.API_URL, self.API_VERSION)
self.session = Session()
self.session.auth = KeyAuth(device_key)
self.session.headers.update({
'Content-Type': 'application/json'
})
def request(self, method, url, **kwargs):
"""Constructs and sends a Request to the Pinaple API."""
full_url = urljoin(self.base_url, url)
if 'data' in kwargs:
kwargs['data'] = self._encode_data(kwargs['data'])
return super(Api, self).request(method, full_url, **kwargs)
def _encode_data(self, data, **kwargs):
"""Returns data encoded as JSON using a custom encoder."""
encoder = JSONEncoder(**kwargs) if kwargs else self._json_encoder
return encoder.encode(data)
def test(self):
url = urljoin(self.base_url, 'functions/test')
response = self.session.get(url)
return response
def login(self):
url = urljoin( self.base_url, 'login' )
response = self.session.post( url )
if response.status_code is not 200:
print('[error] device is not authorized')
exit()
data = response.json()
self.session.auth = SessionAuth(data['session_token'])
示例6: cmd_search_word
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
def cmd_search_word(term):
"""Searches word translations at the http://slovari.yandex.ru.
This command requires `simplejson` module to be installed.
"""
import simplejson
template = """
<ul>
%for v in variants:
<li><a href="/?s=save_word+{{ v['en'].replace(' ', '+') }}%3B+{{ v['ru'].replace(' ', '+').replace(',', '%2C') }}">{{ v['en'] }}</a>
%if v['transcript']:
({{ v['transcript'] }})
%end
%if v['has_audio']:
<object
type="application/x-shockwave-flash"
data="http://audio.lingvo.yandex.net/swf/lingvo/lingvo-player.swf"
width="27"
height="27"
style="visibility: visible;">
<param name="allowscriptaccess" value="always">
<param name="wmode" value="transparent">
<param name="flashvars" value="color=0xFFFFFF&size=27&counter-path=slovari&count=yes&service-url=http://audio.lingvo.yandex.net&download-url-prefix=sounds&timestamp-url-prefix=timestamp.xml&language=SoundEn&sound-file={{ v['en'] }}.mp3">
</object>
%end
— {{ v['ru'] }}</li>
%end
</ul>
%rebase layout title='Word translation'
"""
variants = {}
internet = Session()
for i in reversed(range((len(term) + 1) / 2, len(term) + 1)):
url = 'http://suggest-slovari.yandex.ru/suggest-lingvo?v=2&lang=en&' + \
urllib.urlencode(dict(part=term[:i].encode('utf-8')))
response = internet.get(url)
data = simplejson.loads(response.content)
if data[0]:
for trans, link in zip(*data[1:]):
en, ru = trans.split(' - ', 1)
variants[en] = dict(en=en, ru=ru, link=link)
if len(variants) > 5:
break
def get_spelling(value):
url = 'http://lingvo.yandex.ru/' + force_str(value['en']).replace(' ', '%20') + '/%D1%81%20%D0%B0%D0%BD%D0%B3%D0%BB%D0%B8%D0%B9%D1%81%D0%BA%D0%BE%D0%B3%D0%BE/'
data = internet.get(url).content
xml = ET.fromstring(force_str(data))
transcript = xml.find('*//{x}span[@class="b-translate__tr"]'.format(x=xhtml))
if transcript is None:
value['transcript'] = ''
else:
value['transcript'] = transcript.text
has_audio = xml.find('*//{x}h1[@class="b-translate__word"]//{x}span[@class="b-audio g-js"]'.format(x=xhtml))
value['has_audio'] = has_audio is not None
return value
variants = dict((key, get_spelling(value)) for key, value in variants.iteritems())
return dict(template=template, variants=sorted(variants.values()))
示例7: test_session_HTTPS_200_OK_GET
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
def test_session_HTTPS_200_OK_GET(self):
s = Session()
r = s.get(httpsbin('/'))
self.assertEqual(r.status_code, 200)
示例8: LiteServBase
# 需要導入模塊: from requests.sessions import Session [as 別名]
# 或者: from requests.sessions.Session import get [as 別名]
class LiteServBase(object):
"""Base class that each LiteServ platform need to inherit from.
Look at LiteServMacOSX.py as an example of a plaform implementation
of this. This class provides a few common functions as well as
specifies the API that must be implemented in the subclass."""
def __init__(self, version_build, host, port, storage_engine):
self.version_build = version_build
self.host = host
self.port = port
self.storage_engine = storage_engine
# Used for commandline programs such as net-mono and macosx
self.process = None
# For the subclasses, this property may be a file handle or a string
self.logfile = None
self.session = Session()
self.session.headers['Content-Type'] = 'application/json'
def download(self):
raise NotImplementedError()
def install(self):
raise NotImplementedError()
def start(self, logfile_name):
raise NotImplementedError()
def _verify_not_running(self):
"""
Verifys that the endpoint does not return a 200 from a running service
"""
try:
resp = self.session.get("http://{}:{}/".format(self.host, self.port))
except ConnectionError:
# Expecting connection error if LiteServ is not running on the port
return
log_r(resp)
raise LiteServError("There should be no service running on the port")
def _wait_until_reachable(self):
url = "http://{}:{}".format(self.host, self.port)
count = 0
while count < MAX_RETRIES:
try:
resp = self.session.get(url)
# If request does not throw, exit retry loop
break
except ConnectionError:
log_info("LiteServ may not be launched (Retrying) ...")
time.sleep(1)
count += 1
if count == MAX_RETRIES:
raise LiteServError("Could not connect to LiteServ")
return resp.json()
def _verify_launched(self):
raise NotImplementedError()
def stop(self):
raise NotImplementedError()
def remove(self):
raise NotImplementedError()