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


Python requests.get方法代码示例

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


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

示例1: getTicket

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def getTicket():
    # put the ip address or dns of your apic-em controller in this url
    url = "https://" + controller + "/api/v1/ticket"

    #the username and password to access the APIC-EM Controller
    payload = {"username":"usernae","password":"password"}

    #Content type must be included in the header
    header = {"content-type": "application/json"}

    #Performs a POST on the specified url to get the service ticket
    response= requests.post(url,data=json.dumps(payload), headers=header, verify=False)

    #convert response to json format
    r_json=response.json()

    #parse the json to get the service ticket
    ticket = r_json["response"]["serviceTicket"]

    return ticket 
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:22,代码来源:cisco_apic_em_1.py

示例2: fetch_image

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def fetch_image(self, session, relative, image_url):
        fname = self.file_api.get_file_name(image_url)
        p = os.path.join(relative, fname)
        fetched = False
        try:
            with aiohttp.Timeout(self.timeout):
                async with session.get(image_url) as r:
                    if r.status == 200 and self.file_api.get_file_name(r.url) == fname:
                        c = await r.read()
                        if c:
                            with open(self.file_api.to_abs(p), "wb") as f:
                                f.write(c)
                                fetched = True
        except FileNotFoundError as ex:
            self.logger.error("{0} is not found.".format(p))
        except concurrent.futures._base.TimeoutError as tx:
            self.logger.warning("{0} is timeouted.".format(image_url))
        except Exception as ex:
            self.logger.warning("fetch image is failed. url: {0}, cause: {1}".format(image_url, str(ex)))
        return fetched 
开发者ID:icoxfog417,项目名称:mlimages,代码行数:22,代码来源:__init__.py

示例3: retrieve_top_tor_exit_ips

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def retrieve_top_tor_exit_ips(limit=CLOUDFLARE_ACCESS_RULE_LIMIT):
    """
    Retrieve exit information from Onionoo sorted by consensus weight
    """
    exits = {}
    params = {
        'running': True,
        'flag': 'Exit',
        'fields': 'or_addresses,exit_probability',
        'order': '-consensus_weight',
        'limit': limit
    }
    r = requests.get("https://onionoo.torproject.org/details", params=params)
    r.raise_for_status()
    res = r.json()
    for relay in res.get('relays'):
        or_address = relay.get('or_addresses')[0].split(':')[0]
        exit_probability = relay.get('exit_probability', 0.0)
        # Try calculate combined weight for all relays on each IP
        exits[or_address] = exits.get(or_address, 0.0) + exit_probability
    return sorted(exits, key=exits.get, reverse=True) 
开发者ID:DonnchaC,项目名称:cloudflare-tor-whitelister,代码行数:23,代码来源:whitelist.py

示例4: fetch_access_rules

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [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 
开发者ID:DonnchaC,项目名称:cloudflare-tor-whitelister,代码行数:22,代码来源:whitelist.py

示例5: downloadWithProgress

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def downloadWithProgress(link, outpath):
    print("Downloading %s" % link)
    response = requests.get(link, stream=True)
    total_length = response.headers.get('content-length')

    with open(outpath, "wb") as outf:
        sys.stdout.write("\rDownload progress: [{}]".format(' '*50))
        sys.stdout.flush()

        if total_length is None: # no content length header
            outf.write(response.content)
        else:
            dl = 0
            total_length = int(total_length)
            for data in response.iter_content(chunk_size=1024):
                dl += len(data)
                outf.write(data)
                done = int(50 * dl / total_length)
                sys.stdout.write("\rDownload progress: [{}{}]".format('='*done, ' '*(50-done)))
                sys.stdout.flush()
    sys.stdout.write("\n")
    outf.close() 
开发者ID:svviz,项目名称:svviz,代码行数:24,代码来源:demo.py

示例6: __init__

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def __init__(self, url, method='get', data=None, params=None,
                 headers=None, content_type='application/json', **kwargs):
        self.url = url
        self.method = method
        self.params = params or {}
        self.kwargs = kwargs

        if not isinstance(headers, dict):
            headers = {}
        self.headers = CaseInsensitiveDict(headers)
        if content_type:
            self.headers['Content-Type'] = content_type
        if data:
            self.data = json.dumps(data)
        else:
            self.data = {} 
开发者ID:jumpserver,项目名称:jumpserver-python-sdk,代码行数:18,代码来源:request.py

示例7: read

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def read(uri):
    """Abstract read function.

    EDeN can accept a URL, a file path and a python list.
    In all cases an iterable object should be returned.
    """
    if isinstance(uri, list):
        # test if it is iterable: works for lists and generators, but not for
        # strings
        return uri
    else:
        try:
            # try if it is a URL and if we can open it
            f = requests.get(uri).text.split('\n')
        except ValueError:
            # assume it is a file object
            f = open(uri)
        return f 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:20,代码来源:util.py

示例8: resolve_reference_http

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def resolve_reference_http(cls, design_uri):
        """Retrieve design documents from http/https endpoints.

        Return a byte array of the response content. Support unsecured or
        basic auth

        :param design_uri: Tuple as returned by urllib.parse for the design reference
        """
        if design_uri.username is not None and design_uri.password is not None:
            response = requests.get(
                design_uri.geturl(),
                auth=(design_uri.username, design_uri.password),
                timeout=get_client_timeouts())
        else:
            response = requests.get(
                design_uri.geturl(), timeout=get_client_timeouts())

        return response.content 
开发者ID:airshipit,项目名称:drydock,代码行数:20,代码来源:resolver.py

示例9: resolve_reference_ucp

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def resolve_reference_ucp(cls, design_uri):
        """Retrieve artifacts from a Airship service endpoint.

        Return a byte array of the response content. Assumes Keystone
        authentication required.

        :param design_uri: Tuple as returned by urllib.parse for the design reference
        """
        ks_sess = KeystoneUtils.get_session()
        (new_scheme, foo) = re.subn(r'^[^+]+\+', '', design_uri.scheme)
        url = urllib.parse.urlunparse(
            (new_scheme, design_uri.netloc, design_uri.path, design_uri.params,
             design_uri.query, design_uri.fragment))
        LOG.debug("Calling Keystone session for url %s" % str(url))
        resp = ks_sess.get(url, timeout=get_client_timeouts())
        if resp.status_code >= 400:
            raise errors.InvalidDesignReference(
                "Received error code for reference %s: %s - %s" %
                (url, str(resp.status_code), resp.text))
        return resp.content 
开发者ID:airshipit,项目名称:drydock,代码行数:22,代码来源:resolver.py

示例10: ensure_security_group

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def ensure_security_group(name, vpc, tcp_ingress=frozenset()):
    try:
        security_group = resolve_security_group(name, vpc)
    except (ClientError, KeyError):
        logger.info("Creating security group %s for %s", name, vpc)
        security_group = vpc.create_security_group(GroupName=name, Description=name)
        for i in range(90):
            try:
                clients.ec2.describe_security_groups(GroupIds=[security_group.id])
            except ClientError:
                time.sleep(1)
    for rule in tcp_ingress:
        source_security_group_id = None
        if "source_security_group_name" in rule:
            source_security_group_id = resolve_security_group(rule["source_security_group_name"], vpc).id
        ensure_ingress_rule(security_group, IpProtocol="tcp", FromPort=rule["port"], ToPort=rule["port"],
                            CidrIp=rule.get("cidr"), SourceSecurityGroupId=source_security_group_id)
    return security_group 
开发者ID:kislyuk,项目名称:aegea,代码行数:20,代码来源:__init__.py

示例11: contains

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def contains(self, principal, action, effect, resource):
        for statement in self.policy["Statement"]:
            if "Condition" in statement or "NotAction" in statement or "NotResource" in statement:
                continue

            if statement.get("Principal") != principal or statement.get("Effect") != effect:
                continue

            if isinstance(statement.get("Action"), list):
                actions = set(action) if isinstance(action, list) else set([action])
                if not actions.issubset(statement["Action"]):
                    continue
            elif action != statement.get("Action"):
                continue

            if isinstance(statement.get("Resource"), list):
                resources = set(resource) if isinstance(resource, list) else set([resource])
                if not resources.issubset(statement["Resource"]):
                    continue
            elif resource != statement.get("Resource"):
                continue

            return True 
开发者ID:kislyuk,项目名称:aegea,代码行数:25,代码来源:__init__.py

示例12: get_metadata

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def get_metadata(path):
    res = requests.get("http://169.254.169.254/latest/meta-data/{}".format(path))
    res.raise_for_status()
    return res.content.decode() 
开发者ID:kislyuk,项目名称:aegea,代码行数:6,代码来源:__init__.py

示例13: getNetworkDevices

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def getNetworkDevices(ticket):
    # URL for network device REST API call to get list of existing devices on the network.
    url = "https://" + controller + "/api/v1/network-device"

    #Content type must be included in the header as well as the ticket
    header = {"content-type": "application/json", "X-Auth-Token":ticket}

    # this statement performs a GET on the specified network-device url
    response = requests.get(url, headers=header, verify=False)

    # json.dumps serializes the json into a string and allows us to
    # print the response in a 'pretty' format with indentation etc.
    print ("Network Devices = ")
    print (json.dumps(response.json(), indent=4, separators=(',', ': ')))

  #convert data to json format.
    r_json=response.json()

  #Iterate through network device data and print the id and series name of each device
    for i in r_json["response"]:
        print(i["id"] + "   " + i["series"])

#call the functions 
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:25,代码来源:cisco_apic_em_1.py

示例14: show

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def show(self, ticket):
        """
        通过ticket换取二维码
        详情请参考
        https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542

        :param ticket: 二维码 ticket 。可以通过 :func:`create` 获取到
        :return: 返回的 Request 对象

        使用示例::

            from wechatpy import WeChatClient

            client = WeChatClient('appid', 'secret')
            res = client.qrcode.show('ticket data')

        """
        if isinstance(ticket, dict):
            ticket = ticket["ticket"]
        return requests.get(url="https://mp.weixin.qq.com/cgi-bin/showqrcode", params={"ticket": ticket}) 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:22,代码来源:qrcode.py

示例15: get_url

# 需要导入模块: import requests [as 别名]
# 或者: from requests import get [as 别名]
def get_url(self, media_id):
        """
        获取临时素材

        https://work.weixin.qq.com/api/doc#90000/90135/90254

        :param media_id: 媒体文件id
        :return: 临时素材下载地址
        """
        parts = (
            "https://qyapi.weixin.qq.com/cgi-bin/media/get",
            "?access_token=",
            self.access_token,
            "&media_id=",
            media_id,
        )
        return "".join(parts) 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:19,代码来源:media.py


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