当前位置: 首页>>代码示例>>Python>>正文


Python Session.get方法代码示例

本文整理汇总了Python中requests.Session.get方法的典型用法代码示例。如果您正苦于以下问题:Python Session.get方法的具体用法?Python Session.get怎么用?Python Session.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在requests.Session的用法示例。


在下文中一共展示了Session.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: vote_login

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def vote_login(username, passwd):
    """login in the univs
	Args:
		username: the account name
		passwd: the passwd

	Returns:
		the session

	"""
    try:
        s = Session()
        sso_url = "http://uzone.univs.cn/sso.action"
        sso_data = {}
        sso_data["gUser.loginName"] = username
        sso_data["gUser.password"] = passwd
        r = s.post(sso_url, data=sso_data)
        if not r.content.find("<code>0</code>") > 0:
            return None
        res1 = s.get("http://mzml.univs.cn:8081/common/checkcode")
        code = json.loads(res1.content)
        check_sso_url = "http://uzone.univs.cn/checkSSOLogin.action?token=%s&subSiteId=%s&checkCode=%s&returnUrl=http://mzml.univs.cn:8081/land.html"
        res2 = s.get(check_sso_url % (code["data"]["date"], code["data"]["subSiteId"], code["data"]["checkout"]))
        codes = res2.url
        sign_in = "http://mzml.univs.cn:8081/user/sigin"
        sign_data = {}
        sign_data["uid"] = codes.split("?")[1].split("&")[1].split("=")[1]
        sign_data["token"] = code["data"]["date"]
        sign_data["checkcode"] = codes.split("?")[1].split("&")[0].split("=")[1]
        s.post(sign_in, data=sign_data)
        return s
    except ConnectionError, Timeout:
        logging.exception("Timeout" + username)
        return 1
开发者ID:mrzhangboss,项目名称:autovote,代码行数:36,代码来源:vote.py

示例2: search

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def search(apn):
    s = Session()
    s.mount('https://', HTTPSAdapter())
    url = 'https://www.acgov.org/ptax_pub_app/RealSearch.do'
    data = {
        'displayApn': apn,
        'situsStreetNumber': '',
        'situsStreetName': '',
        'situsStreetSuffix': '',
        'situsUnitNumber': '',
        'situsCity': '',
        'searchBills': 'Search',
        'showHistory': 'N',
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36',
    }
    s.get('https://www.acgov.org/ptax_pub_app/RealSearchInit.do?showSearchParmsFromLookup=true', headers = headers)
    r = s.post(url, data = data)
    try:
        os.mkdir('results')
    except OSError:
        pass

    f = open(os.path.join('results', apn), 'w')
    f.write(r.text)
    f.close()
开发者ID:tlevine,项目名称:alameda-houses,代码行数:29,代码来源:houses.py

示例3: get

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
    def get(self):
        session = Session()
        availabilityJSON = session.get(iPhone6AvailabilityURL).content
        availabilityDict = json.loads(availabilityJSON)

        caStoresXML = session.get(appleCAStoreURL).content
        # self.write(caStoresXML)
        storesDict = xmltodict.parse(caStoresXML)["records"]["country"]
        # self.dumpJSON(storesDict)
        ontarioStoresList = []
        for eachStateDict in storesDict["state"]:
            if eachStateDict["@name"] == "Ontario":
                ontarioStoresList = eachStateDict["store"]
        # self.dumpJSON(ontarioStoresList)
        # self.write(storeNameForStoreID(ontarioStoresList, "R447"))

        # # logging.info(availabilityDict)
        lastUpdatedTimestamp = availabilityDict.pop("updated")
        storeIDs = availabilityDict.keys()
        for storeID in storeIDs:
            phonesDictInThisStore = availabilityDict[storeID]
            phoneKeys = phonesDictInThisStore.keys()
            for eachPhoneKey in phoneKeys:
                if (phonesDictInThisStore[eachPhoneKey] == True) and (eachPhoneKey in targetModels) and (storeID in targetStores):
                    sendEmail(storeNameForStoreID(ontarioStoresList, storeID), eachPhoneKey)
                if eachPhoneKey in iphone6Dictionary:
                    replaceKeyInDictionary(phonesDictInThisStore, eachPhoneKey, iphone6Dictionary[eachPhoneKey])
        
        for storeID in storeIDs:
            replaceKeyInDictionary(availabilityDict, storeID, storeNameForStoreID(ontarioStoresList, storeID))

        availabilityDict["_updated"] = lastUpdatedTimestamp    
        orderedDict = collections.OrderedDict(sorted(availabilityDict.items()))
        self.dumpJSON(orderedDict)
开发者ID:honghaoz,项目名称:Reserve-iPhone6-Availability-Monitor,代码行数:36,代码来源:main.py

示例4: main

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def main():
    for user in create_login_payload():
        logging.info('Opening a Grafana session...')
        session = Session()
        login(session, user)

        if check_initialized(session):
            logging.info('Grafana has already been initialized, skipping!')
            return

        logging.info('Attempting to add configured datasource...')
        r = session.post('{url}/api/datasources'.format(url=GRAFANA_URL),
                         json=create_datasource_payload())
        logging.debug('Response: %r', r.json())
        r.raise_for_status()

        for path in sorted(glob.glob('{dir}/*.json'.format(dir=DASHBOARDS_DIR))):
            logging.info('Creating dashboard from file: {path}'.format(path=path))
            r = session.post('{url}/api/dashboards/db'.format(url=GRAFANA_URL),
                             json=create_dashboard_payload(path))
            logging.debug('Response: %r', r.json())
            r.raise_for_status()

        logging.info('Ending %r session...', user.get('user'))
        session.get('{url}/logout'.format(url=GRAFANA_URL))

    logging.info('Finished successfully.')
开发者ID:hpcloud-mon,项目名称:monasca-docker,代码行数:29,代码来源:grafana.py

示例5: sendMicrosoft

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def sendMicrosoft(filename, help_text, email, name):
    br = Session()
    hostUrl = "https://www.microsoft.com/en-us/security/portal/submission/submit.aspx"
    br.headers.update({'referer': hostUrl})
    page = br.get(hostUrl)

    br.get("http://c.microsoft.com/trans_pixel.aspx")  # get additional cookies

    page = BeautifulSoup(page.text, 'html.parser')
    form = page.find('form', id='Newsubmission')

    form_data = dict([(el['name'], el.get('value', None))
                      for el in form.find_all('input') if el.has_attr('name')])

    form_data["Name"] = email
    form_data["Product"] = "Windows Server Antimalware"
    form_data["Comments"] = help_text
    form_data["Priority"] = 2

    response = br.post(
        hostUrl, data=form_data,
        files={u'File':
               open(filename, 'rb')})

    text = response.text.encode('utf-8')

    result = text.find('window.location.href="SubmissionHistory.aspx')
    if result != -1:
        sub_url = text[result + 44:]
        sub_url = "/SubmissionHistory.aspx" + sub_url[:sub_url.find('"')]
        url = response.url[:response.url.rfind('/')] + sub_url
        return 0, "Success! Your status is <a href='%s'>here</a>" % url
    else:
        logger.warning("Microsoft error: %s" % text)
        return 1, "Something wrong: %s" % text
开发者ID:m-messiah,项目名称:cuckoo,代码行数:37,代码来源:share.py

示例6: get_all_setlists

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def get_all_setlists(artist, page_number, sets_per_page):
    headers = {'Accept': 'application/json'}
    url = "http://api.setlist.fm/rest/0.1/search/setlists?artistName={0}&p={1}".format(artist, page_number)
    session = Session()
    response = session.get(url, headers=headers)
    data = response.json()

    setlists = data['setlists']['setlist']
    total = data['setlists']['@total']
    total_pages = math.ceil(int(total) / sets_per_page)

    # Continue to make requests until max setlists are downloaded
    for page in range(page_number + 1, total_pages + 1):
        print('{0} Page {1}'.format(artist, page))
        url = "http://api.setlist.fm/rest/0.1/search/setlists?artistName={0}&p={1}".format(artist, page)
        response = session.get(url, headers=headers)
        data = response.json()

        # If more than one result, concatenate lists, else append element to list.
        if type(data['setlists']['setlist']) is list:
            setlists = setlists + data['setlists']['setlist']
        elif type(data['setlists']['setlist']) is dict:
            setlists.append(data['setlists']['setlist'])

    return setlists
开发者ID:DJO3,项目名称:setlist_visualizer,代码行数:27,代码来源:get_setlists.py

示例7: hit_example_com

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [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)
开发者ID:fbarquero,项目名称:locust_swPerf,代码行数:28,代码来源:locustfile.py

示例8: upload

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
    def upload(cls, url, f, filename=None, session=None):
        if session is None:
            session = Session()

        should_close = True

        if isinstance(f, six.string_types):
            if not filename:
                filename = os.path.basename(f)

            f = open(f, 'rb')
            should_close = True

        try:
            if 'csrftoken' not in session.cookies:
                session.get('http://databasin.org')

            r = session.post(
                url, data={'csrfmiddlewaretoken': session.cookies['csrftoken']}, files={'file': (filename, f)}
            )
            raise_for_authorization(r, session.client.username is not None)
            r.raise_for_status()

            o = urlparse(url)
            return cls.get(
                '{0}://{1}{2}'.format(o.scheme, o.netloc, TEMPORARY_FILE_DETAIL_PATH.format(uuid=r.json()['uuid'])),
                session=session,
                lazy=False
            )
        finally:
            if should_close:
                f.close()
开发者ID:consbio,项目名称:python-databasin,代码行数:34,代码来源:uploads.py

示例9: JoolaBaseClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
class JoolaBaseClient(object):
    def __init__(self, base_url, credentials=None, api_token=None, **kwargs):
        self.base_url = str(base_url)
        self.session = Session()

        self.session.mount('http://', CachingHTTPAdapter())
        self.session.mount('https://', CachingHTTPAdapter())

        if api_token:
            self.session.auth = APITokenAuth(api_token)
        elif credentials:
            self.session.auth = credentials

    def list(self):
        return self.session.get(self.base_url)

    def get(self, lookup):
        return self.session.get('%s%s' % (self.base_url, str(lookup)))

    def insert(self, **kwargs):
        return self.session.post(self.base_url, data=kwargs)

    def patch(self, lookup, **kwargs):
        return self.session.patch('%s%s' % (self.base_url, str(lookup)), data=kwargs)

    def delete(self, lookup):
        return self.session.delete('%s%s' % (self.base_url, str(lookup)))
开发者ID:joola,项目名称:joola.io.sdk-python,代码行数:29,代码来源:client.py

示例10: gen_session

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def gen_session():
    session = Session()
    url = 'http://www.sccredit.gov.cn/queryInfo.do?behavior=enterSearch&panel=corp'
    try:
        session.get(url, timeout=3)
        return session
    except Exception:
        pass
开发者ID:alingse,项目名称:verifycode,代码行数:10,代码来源:down_image.py

示例11: test_login_logout

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
def test_login_logout():
    s = Session()
    rt = s.get(url('fl'))
    assert_response(rt, 'Login OK')
    rt = s.get(url('whoami'))
    assert_response(rt, common.FAKE_USER)
    s.get(url('logout'))
    rt = s.get(url('whoami'))
    assert_response(rt, None, status=401)
开发者ID:wolf0403,项目名称:flask-boilerplate,代码行数:11,代码来源:test.py

示例12: update_analytics

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
    def update_analytics(self):

        session = Session()

        if 'TWITLOG_COOKIES' in os.environ:
            cookies = json.loads(os.environ['TWITLOG_COOKIES'])
            session.cookies.update(cookies)

        else:

            print 'Fetching homepage for auth token'
            res = session.get('https://twitter.com')

            body = BeautifulSoup(res.text)
            input_ = body.find(lambda tag: tag.name == 'input' and tag.get('name') == 'authenticity_token')
            authe_token = input_['value']


            print 'Logging into account'
            res = session.post('https://twitter.com/sessions', data={
                'session[username_or_email]': self.args.username,
                'session[password]': self.args.password,
                'return_to_ssl': 'true',
                'scribe_log': '',
                'redirect_after_login': '/',
                'authenticity_token': authe_token,
            })

            cookies = dict(session.cookies.iteritems())
            print
            print 'export TWITLOG_COOKIES=\'%s\'' % json.dumps(cookies)
            print

        with self.db.connect() as con:
            for tid, old_json in con.execute('''
                SELECT tweet.id, last.json
                FROM tweets as tweet
                LEFT JOIN tweet_metrics as last
                ON tweet.last_metrics_id = last.id
                WHERE tweet.last_metrics_id IS NULL OR
                    last.created_at > datetime('now','-1 day')
                ORDER BY tweet.id DESC
            '''):
                res = session.get('https://twitter.com/i/tfb/v1/tweet_activity/web/poll/%s' % tid)
                new_metrics = {k: int(v) for k, v in res.json()['metrics']['all'].iteritems()}
                new_metrics.pop('Engagements', None) # Just a total of the others.
                new_json = json.dumps(new_metrics, sort_keys=True)
                changed = new_json != old_json
                print tid, new_json if changed else 'unchanged'
                if changed:
                    mid = con.insert('tweet_metrics', {
                        'tweet_id': tid,
                        'json': new_json,
                    })
                    con.update('tweets', {'last_metrics_id': mid}, {'id': tid})
                    con.commit()
开发者ID:mikeboers,项目名称:TwitLog,代码行数:58,代码来源:analytics.py

示例13: Compranet

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
class Compranet(FishFinder):
  
  def setup(self):
    self.session = Session()
    self.session.get('http://compranet-pa.funcionpublica.gob.mx/PAAASOP/buscador.jsp')
    self.post_url = 'http://compranet-pa.funcionpublica.gob.mx/PAAASOP/DownloadArchivo'

  def write_xls(self, data, filename):
    with open(filename, 'wb') as f:
      f.write(data)
  
  def search(self, query):
    """
    Submit a search query and return results
    """
    params = {
      'ocultarParam':'0',
      'ocultarDetalle':'1',
      'cveEntFederativa':'0',
      'cveDependencia':'0',
      'concepto': query,
      'valCompraDirPyme':'1000',
      'entidadesSelect':'0',
      'dependenciasSelect':'0'
    }
    r = self.session.post(self.post_url, params = params)
    return r.content

  def test(self, result, query):
    """
    With our results, test 
    whethere the query was legitimate.
    0 = No Results
    1 = Pass 
    2 = Needs More 
    """
    xls = xlrd.open_workbook(file_contents=result)
    sheet = xls.sheet_by_index(0)
    nrows = sheet.nrows 

    if nrows == 1:
      print "%s has no results" % query
      return 0

    elif nrows < 2501:
      filename = "data/%s.xls" % query
      print "Writing %s" % filename
      self.write_xls(result, filename)
      return 1 

    else:
      print "%s has too many results" % query
      return 2
开发者ID:abelsonlive,项目名称:fishfinder,代码行数:55,代码来源:compranet.py

示例14: TheSubDBProvider

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [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)
开发者ID:ArthurGarnier,项目名称:SickRage,代码行数:53,代码来源:thesubdb.py

示例15: ModelRegistryClient

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import get [as 别名]
class ModelRegistryClient(object):
    def __init__(self, host_and_port):
        self.endpoint = "http://%s/api/v1/models/" % host_and_port
        self.session = Session()

    def retrieve_model(self, slug, timestamp, destination):
        response = self.session.get("%s/%s/%s/default/model.bin" % (self.endpoint, slug, timestamp))
        response.raise_for_status()
        data = StringIO.StringIO(response.content)
        z = zipfile.ZipFile(data)
        z.extractall(destination)
        metadata = self.session.get("%s/%s/%s/default/metadata" % (self.endpoint, slug, timestamp))
        metadata.raise_for_status()
        return metadata.json()
开发者ID:CognitiveScale,项目名称:industry-models,代码行数:16,代码来源:service_clients.py


注:本文中的requests.Session.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。