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


Python Session.json方法代码示例

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


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

示例1: pkgcloud_api_call

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
def pkgcloud_api_call(url, method, **kwargs):
    """
    Generic method to make HTTP requests to packagecloud
    """
    resp = None
    attempt = 0
    req = Request(method.upper(), url, **kwargs)

    while True:
        try:
            attempt += 1
            resp = Session().send(
                Session().prepare_request(req), verify=True)
            resp.raise_for_status()
            break
        except (HTTPError, ConnectionError, Timeout) as ex:
            if attempt >= 10:
                utils.abort(ex.message)
            else:
                time.sleep(3)
                continue
        except RequestException as ex:
            utils.abort(ex.message)

    try:
        if "error" in resp.json():
            raise Exception('{}'.format(resp.json()['error']))
        return resp
    except ValueError as ex:
        utils.abort("Unexpected response from packagecloud API. "
                    "Expected json, got something else: {}".format(ex.message))
    except Exception as ex:
        utils.abort("Error making packagecloud API call: {}".format(ex.message))
开发者ID:pwyliu,项目名称:packagecloud-poll,代码行数:35,代码来源:pkgcloudapi.py

示例2: run

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
    def run(self, module, target, expr_form, args, **kwargs):
        self.verify_ssl = self.config.get('verify_ssl', True)
        '''
        CLI Examples:

            st2 run salt.local module=test.ping matches='web*'
            st2 run salt.local module=test.ping expr_form=grain target='os:Ubuntu'
        '''
        if module not in ['test.ping','test.version']:
            self.generate_package('local',
                                  cmd=module,
                                  target=target,
                                  expr_form=expr_form,
                                  args=args,
                                  data=kwargs)
        else:
            self.generate_package('local',
                                  cmd=module,
                                  target=target,
                                  expr_form=expr_form,
                                  args=None,
                                  data=kwargs)
            
        request = self.generate_request()
        self.logger.info('[salt] Request generated')
        request.prepare_body(json.dumps(self.data), None)
        self.logger.info('[salt] Preparing to send')
        resp = Session().send(request, verify=self.verify_ssl)
        return resp.json()
开发者ID:zanhsieh,项目名称:showcase-salt-chatops,代码行数:31,代码来源:local.py

示例3: run

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
    def run(self, module, **kwargs):
        _cmd = module
        """
        CLI Examples:

            st2 run salt.runner_jobs.active
            st2 run salt.runner_jobs.list_jobs
        """
        self.generate_package("runner", cmd=_cmd)
        if kwargs["kwargs"] is not None:
            self.data.update(kwargs["kwargs"])
        request = self.generate_request()
        request.prepare_body(json.dumps(self.data), None)
        resp = Session().send(request, verify=True)
        return resp.json()
开发者ID:orius123,项目名称:st2contrib,代码行数:17,代码来源:runner.py

示例4: run

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
    def run(self, **kwargs):
        '''
        CLI Examples:

            st2 run salt.runner matches='web*' module=test.ping
            st2 run salt.client module=pkg.install \
                    kwargs='{"pkgs":["git","httpd"]}'
        '''
        # TODO: This is broken, fix it. I temporary disabled it to avoid pylint
        # failure.
        # Also "args" and "kwargs" action parameters are unused?
        # self.generate_package(cmd=cmd)
        request = self.generate_request()
        request.prepare_body(json.dumps(self.data), None)
        resp = Session().send(request, verify=True)
        return resp.json()
开发者ID:orius123,项目名称:st2contrib,代码行数:18,代码来源:local.py

示例5: run

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
    def run(self, module, target, **kwargs):
        '''
        CLI Examples:

            st2 run salt.runner matches='web*' module=test.ping
            st2 run salt.client module=pkg.install \
                    kwargs='{"pkgs":["git","httpd"]}'
        '''
        # TODO: This is broken, fix it. I temporary disabled it to avoid pylint
        # failure.
        # Also "args" and "kwargs" action parameters are unused?
        # self.generate_package(cmd=cmd)
        _cmd = module
        self.generate_package('local', cmd=_cmd)
        if kwargs['kwargs'] is not None:
            self.data.update(arg['arg'])
        if target is not None:
        	target = target.replace('http://','')
        	self.data['tgt'] = target

        request = self.generate_request()
        request.prepare_body(json.dumps(self.data), None)
        resp = Session().send(request, verify=True)
        return resp.json()
开发者ID:Jamezz,项目名称:st2contrib,代码行数:26,代码来源:local.py

示例6: get_njobs_in_queue

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
 def get_njobs_in_queue(self, username=None):
     if username is None:
         username = getpass.getuser()
     from requests import Session  # hide import in case optional library not installed
     r = Session().get("https://newt.nersc.gov/newt/queue/{}/?user={}".format(self.resource, username))
     return len(r.json())
开发者ID:digitalsatori,项目名称:fireworks,代码行数:8,代码来源:pbs_newt_adapter.py

示例7: reindex

# 需要导入模块: from requests import Session [as 别名]
# 或者: from requests.Session import json [as 别名]
def reindex(host, handler, core, swap_core, core_admin='admin/cores', output_stream=sys.stderr):
    try:
        base_url = url(host, core, handler)
        index_req = Request('GET', base_url, params={'wt': 'json', 'command': 'full-import', 'clean':'true'}).prepare()
        test_req = Request('GET', base_url, params={'wt': 'json'}).prepare()
        optimize_req = Request('GET', base_url, params={'wt': 'json', 'optimize': 'true'}).prepare()
        
        numdocs_estimate = 1
        if swap_core:
            swap_req = Request('GET', url(host, core_admin), params={
                    'wt': 'json', 
                    'action': 'swap', 
                    'core': core, 
                    'other': swap_core}
            ).prepare()
            try:
                # use "other" core if we're going to swap
                numdocs_estimate = get(url(host, swap_core, 'select'), 
                        params={'wt': 'json', 'rows': '0', 'q': '*:*'}).json()['response']['numFound']
            except:
                pass
        else:
            try:
                # use index core otherwise
                numdocs_estimate = get(url(host, core, 'select'), 
                        params={'wt': 'json', 'rows': '0', 'q': '*:*'}).json()['response']['numFound']
            except:
                pass
            
        # start index process
        logging.info("Starting search index")
        try:
            resp = Session().send(index_req)
        except Exception as e:
            logging.exception(e)
            logging.debug(resp.url)
        if resp.status_code != 200:
            raise Exception("%s\n\nIndexing Failed!, response code: (%d) with body:\n%s" % (resp.url, resp.status_code, resp.text))

        # poll every minute until Indexing Complete or error
        test_session = Session()
        while True:
            sleep(60)
            resp = test_session.send(test_req)
            logging.debug("Testing DIH for completion...")
            if resp.status_code != 200:
                logging.warning("Solr DIH failed!, response code: (%d) with body:\n%s" % (resp.status_code, resp.text))
                continue
            
            data = resp.json()
            
            if data['status'] == 'busy':
                done = int(data['statusMessages']['Total Documents Processed'])
                if done > 0 and done < numdocs_estimate:
                    progbar_update(float(done) / numdocs_estimate, output_stream) 
                elif done > 0:
                    print >> output_stream, "%d docs completed" % done
                continue

            if data['statusMessages'][''].startswith('Indexing completed'):
                logging.debug("...DIH complete")
                break

            if data['status'] not in ('idle', 'busy'):
                logging.debug("Indexing Failed!")
                raise Exception("Indexing Failed!, response code: (%d) with body:\n%s" % (resp.status_code, resp.text))

        # optimize index
        logging.debug("Optimising Index")
        resp = Session().send(optimize_req)
        if resp.status_code != 200:
            raise Exception("Optimize Failed!, response code: (%d) with body:\n%s" % (resp.status_code, resp.text))

        # swap secondary index with main index
        logging.debug("Swapping Cores")
        resp = Session().send(swap_req)
        if resp.status_code != 200:
            raise Exception("Core Swap Failed!, response code: (%d) with body:\n%s" % (resp.status_code, resp.text))

        logging.info("Search index complete")
    except KeyboardInterrupt:
        from pprint import pformat as pp
        print >> output_stream, "\n" + pp(get(base_url, params={'wt': 'json', 'command': 'abort'}).json())
    except Exception, ex:
        logging.exception(ex)
开发者ID:spuriousdata,项目名称:django-brushfire,代码行数:87,代码来源:reindex.py


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