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


Python urllib2.splituser函数代码示例

本文整理汇总了Python中urllib2.splituser函数的典型用法代码示例。如果您正苦于以下问题:Python splituser函数的具体用法?Python splituser怎么用?Python splituser使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: open_with_auth

def open_with_auth(url):
    """
    Open a urllib2 request, handling HTTP authentication
    """
    import config

    scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
    assert not query
    auth, host = urllib2.splituser(netloc)
    if auth:
        auth = urllib2.unquote(auth).encode('base64').strip()
    elif 'enthought.com/repo/' in url and 'repo/pypi/eggs/' not in url:
        auth = config.get('EPD_auth')
        if auth is None:
            userpass = config.get('EPD_userpass')
            if userpass:
                auth = userpass.encode('base64').strip()

    if auth:
        new_url = urlparse.urlunparse((scheme, host, path,
                                       params, query, frag))
        request = urllib2.Request(new_url)
        request.add_header("Authorization", "Basic " + auth)
        logger.debug('Requesting %s with auth' % new_url)
    else:
        request = urllib2.Request(url)
        logger.debug('Requesting %s without auth' % url)
    request.add_header('User-Agent', 'enstaller/%s' % __version__)
    return urllib2.urlopen(request)
开发者ID:jdmarch,项目名称:enstaller,代码行数:29,代码来源:utils.py

示例2: download

    def download(self, source, dest):
        """
        Download an archive file.

        :param str source: URL pointing to an archive file.
        :param str dest: Local path location to download archive file to.
        """
        # propogate all exceptions
        # URLError, OSError, etc
        proto, netloc, path, params, query, fragment = urlparse.urlparse(source)
        if proto in ('http', 'https'):
            auth, barehost = urllib2.splituser(netloc)
            if auth is not None:
                source = urlparse.urlunparse((proto, barehost, path, params, query, fragment))
                username, password = urllib2.splitpasswd(auth)
                passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
                # Realm is set to None in add_password to force the username and password
                # to be used whatever the realm
                passman.add_password(None, source, username, password)
                authhandler = urllib2.HTTPBasicAuthHandler(passman)
                opener = urllib2.build_opener(authhandler)
                urllib2.install_opener(opener)
        response = urllib2.urlopen(source)
        try:
            with open(dest, 'w') as dest_file:
                dest_file.write(response.read())
        except Exception as e:
            if os.path.isfile(dest):
                os.unlink(dest)
            raise e
开发者ID:chuckbutler,项目名称:shoutcast-charm,代码行数:30,代码来源:archiveurl.py

示例3: get_transport_and_path_from_url

def get_transport_and_path_from_url(url, config=None, **kwargs):
    """Obtain a git client from a URL.

    :param url: URL to open (a unicode string)
    :param config: Optional config object
    :param thin_packs: Whether or not thin packs should be retrieved
    :param report_activity: Optional callback for reporting transport
        activity.
    :return: Tuple with client instance and relative path.
    """
    parsed = urlparse.urlparse(url)
    auth, host = urllib2.splituser(parsed.netloc)
    if parsed.scheme == 'git':
        return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
                parsed.path)
    elif parsed.scheme in ('git+ssh', 'ssh'):
        path = parsed.path
        if path.startswith('/'):
            path = parsed.path[1:]
        return SSHGitClient(parsed.hostname, port=parsed.port,
                            username=parsed.username, **kwargs), path
    elif parsed.scheme in ('http', 'https'):
        base_url = urlparse.urlunparse(parsed._replace(netloc=host))
        return HttpGitClient(base_url, config=config, user=parsed.username, 
                             passwd=parsed.password, **kwargs), parsed.path
    elif parsed.scheme == 'file':
        return default_local_git_client_cls(**kwargs), parsed.path

    raise ValueError("unknown scheme '%s'" % parsed.scheme)
开发者ID:DocVaughan,项目名称:Pythonista,代码行数:29,代码来源:client.py

示例4: open_with_auth

def open_with_auth(url):
    """Open a urllib2 request, handling HTTP authentication"""

    scheme, netloc, path, params, query, frag = urlparse.urlparse(url)

    if scheme in ('http', 'https'):
        auth, host = urllib2.splituser(netloc)
    else:
        auth = None

    if auth:
        auth = "Basic " + urllib2.unquote(auth).encode('base64').strip()
        new_url = urlparse.urlunparse((scheme,host,path,params,query,frag))
        request = urllib2.Request(new_url)
        request.add_header("Authorization", auth)
    else:
        request = urllib2.Request(url)

    request.add_header('User-Agent', user_agent)
    fp = urllib2.urlopen(request)

    if auth:
        # Put authentication info back into request URL if same host,
        # so that links found on the page will work
        s2, h2, path2, param2, query2, frag2 = urlparse.urlparse(fp.url)
        if s2==scheme and h2==host:
            fp.url = urlparse.urlunparse((s2,netloc,path2,param2,query2,frag2))

    return fp
开发者ID:ahendy0,项目名称:Holdem,代码行数:29,代码来源:package_index.py

示例5: open_with_auth

def open_with_auth(url):
    """Open a urllib2 request, handling HTTP authentication"""

    scheme, netloc, path, params, query, frag = urlparse.urlparse(url)

    # Double scheme does not raise on Mac OS X as revealed by a
    # failing test. We would expect "nonnumeric port". Refs #20.
    if netloc.endswith(':'):
        raise httplib.InvalidURL("nonnumeric port: ''")

    if scheme in ('http', 'https'):
        auth, host = urllib2.splituser(netloc)
    else:
        auth = None

    if auth:
        auth = "Basic " + _encode_auth(auth)
        new_url = urlparse.urlunparse((scheme,host,path,params,query,frag))
        request = urllib2.Request(new_url)
        request.add_header("Authorization", auth)
    else:
        request = urllib2.Request(url)

    request.add_header('User-Agent', user_agent)
    fp = urllib2.urlopen(request)

    if auth:
        # Put authentication info back into request URL if same host,
        # so that links found on the page will work
        s2, h2, path2, param2, query2, frag2 = urlparse.urlparse(fp.url)
        if s2==scheme and h2==host:
            fp.url = urlparse.urlunparse((s2,netloc,path2,param2,query2,frag2))

    return fp
开发者ID:Cfwang1337,项目名称:keyword_parser_heroku,代码行数:34,代码来源:package_index.py

示例6: _open_url

    def _open_url(self, url):
        """Open a urllib2 request, handling HTTP authentication, and local
        files support.

        """
        scheme, netloc, path, params, query, frag = urlparse.urlparse(url)

        # authentication stuff
        if scheme in ('http', 'https'):
            auth, host = urllib2.splituser(netloc)
        else:
            auth = None

        # add index.html automatically for filesystem paths
        if scheme == 'file':
            if url.endswith(os.path.sep):
                url += "index.html"

        # add authorization headers if auth is provided
        if auth:
            auth = "Basic " + \
                urlparse.unquote(auth).encode('base64').strip()
            new_url = urlparse.urlunparse((
                scheme, host, path, params, query, frag))
            request = urllib2.Request(new_url)
            request.add_header("Authorization", auth)
        else:
            request = urllib2.Request(url)
        request.add_header('User-Agent', USER_AGENT)
        try:
            fp = urllib2.urlopen(request)
        except (ValueError, httplib.InvalidURL), v:
            msg = ' '.join([str(arg) for arg in v.args])
            raise PackagingPyPIError('%s %s' % (url, msg))
开发者ID:dstufft,项目名称:distutils2,代码行数:34,代码来源:simple.py

示例7: get_proxy_info

def get_proxy_info(proxystr=""):
    """
    Get proxy config from string or environment variables.

    If a proxy string is passed in, it overrides whatever might be in the
    environment variables.

    Returns dictionary of identified proxy information, or None if proxystr was
    empty and no config was found fmor os.environ

    Raises InvalidConfiguration on any configuration error.

    """
    if proxystr == "":
        # FIXME: We should be supporting http_proxy, HTTP_PROXY variables.
        proxy_info = {
            'host' : os.environ.get('PROXY_HOST', None),
            'port' : _convert_port_value(os.environ.get('PROXY_PORT', None)),
            'user' : os.environ.get('PROXY_USER', None),
            'pass' : os.environ.get('PROXY_PASS', None)
            }
        if proxy_info.get("host") is None:
            return None
    else:
        parts = urlparse.urlparse(proxystr)
        if parts.netloc == "":
            proxystr = "http://{0}".format(proxystr)
            parts = urlparse.urlparse(proxystr)

        _, hostport = urllib2.splituser(parts.netloc)
        host, _ = urllib2.splitport(hostport)

        host = urlparse.urlunparse((parts.scheme, host, "", "", "", ""))

        proxy_info = {
            'host' : host,
            'port' : _convert_port_value(parts.port),
            'user' : parts.username,
            'pass' : parts.password,
            }

    # If a user was specified, but no password was, prompt for it now.
    user = proxy_info.get('user', None)
    if user is not None and len(user) > 0:
        passwd = proxy_info.get('pass', None)
        if passwd is None or len(passwd) < 1:
            import getpass
            proxy_info['pass'] = getpass.getpass()

    if proxy_info["host"] is None or len(proxy_info["host"]) < 1:
        error_msg = ("Invalid proxy configuration '{0}': "
                     "proxy string should be of the form "
                     "'http://host:port' or 'http://host'".format(proxystr))
        raise InvalidConfiguration(error_msg)

    return proxy_info
开发者ID:dmsurti,项目名称:enstaller,代码行数:56,代码来源:util.py

示例8: open_url

def open_url(url):
    """
    Open a urllib2 request, handling HTTP authentication
    """
    scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
    assert not query
    auth, host = urllib2.splituser(netloc)

    request = urllib2.Request(url)
    request.add_header("User-Agent", "IronPkg/%s" % __version__)
    return urllib2.urlopen(request)
开发者ID:pombredanne,项目名称:ironpkg,代码行数:11,代码来源:utils.py

示例9: _getBaseDownloadUrl

 def _getBaseDownloadUrl(self):
     """
     Return the base URL relative to which to download images,
     removing any user/password information, and using http
     """
     # extract the downloadImage base url from the serverUrl configuration
     parts = list(urllib2.urlparse.urlparse(self.rbuilderUrl))
     parts[1] = urllib2.splituser(parts[1])[1]
     # FIXME: is this whole ../ business a workaround for splitbrain rBO?
     parts[2] = parts[2] and parts[2] or "/"
     return "http://%s%s" % (parts[1], util.normpath(parts[2] + "../")[1:])
开发者ID:pombredanne,项目名称:rbuild,代码行数:11,代码来源:rbuilderfacade.py

示例10: set_site

 def set_site(cls, value):
     cls._threadlocal.connection = None
     ShopifyResource._site = cls._threadlocal.site = value
     if value is not None:
         host = urlparse.urlsplit(value)[1]
         auth_info, host = urllib2.splituser(host)
         if auth_info:
             user, password = urllib2.splitpasswd(auth_info)
             if user:
                 cls.user = urllib.unquote(user)
             if password:
                 cls.password = urllib.unquote(password)
开发者ID:deniszgonjanin,项目名称:shopify_python_api,代码行数:12,代码来源:base.py

示例11: set_site

 def set_site(cls, value):
     if value is not None:
         host = urlparse.urlsplit(value)[1]
         auth_info, host = urllib2.splituser(host)
         if auth_info:
             user, password = urllib2.splitpasswd(auth_info)
             if user:
                 cls._user = urllib.unquote(user)
             if password:
                 cls._password = urllib.unquote(password)
     cls._connection = None
     cls._site = value
开发者ID:roninio,项目名称:gae-shopify-python-boilerplate,代码行数:12,代码来源:activeresource.py

示例12: __init__

 def __init__(self, url):
     self.url = url
     self.schema, url = urllib2.splittype(url)
     host, path = urllib2.splithost(url)
     userpass, host = urllib2.splituser(host)
     if userpass:
         self.user, self.password = urllib2.splitpasswd(userpass)
     path, self.querystring = urllib.splitquery(path)
     self.query = self.querystring and self.querystring.split('&') or []
     #urllib.splitquery(url)
     self.host, self.port = urllib2.splitport(host)
     path, self.tag = urllib2.splittag(path)
     self.path = path.strip('/')
开发者ID:TheOstrichIO,项目名称:tomato-cmd,代码行数:13,代码来源:common.py

示例13: _inject_credentials

def _inject_credentials(url, username=None, password=None):
    """Used by `inject_credentials` decorators to actually do the injecting"""

    if username and password:
        scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
        if scheme in ('http', 'https'):
            auth_part, host_part = urllib2.splituser(netloc)
            if not auth_part: # If the URL doesn't have credentials in it already
                netloc = '%s:%[email protected]%s' % (
                    urllib.quote(username, ''),
                    urllib.quote(password, ''),
                    host_part,
                )
                url = urlparse.urlunparse((scheme,netloc,path,params,query,frag))
    return url
开发者ID:niteoweb,项目名称:isotoma.buildout.basicauth,代码行数:15,代码来源:download.py

示例14: _parse_site

    def _parse_site(self, site):
        """Retrieve the auth information and base url for a site.

        Args:
            site: The URL to parse.
        Returns:
            A tuple containing (site, username, password).
        """
        proto, host, path, query, fragment = urlparse.urlsplit(site)
        auth_info, host = urllib2.splituser(host)
        if not auth_info:
            user, password = None, None
        else:
            user, password = urllib2.splitpasswd(auth_info)

        new_site = urlparse.urlunparse((proto, host, '', '', '', ''))
        return (new_site, user, password)
开发者ID:Chris2Brooks,项目名称:Securiace-ERPNext-easy-installer,代码行数:17,代码来源:connection.py

示例15: urlretrieve

 def urlretrieve(url, tmp_path):
     """Work around Python issue 24599 includig basic auth support
     """
     scheme, netloc, path, params, query, frag = urlparse(url)
     auth, host = urllib2.splituser(netloc)
     if auth:
         url = urlunparse((scheme, host, path, params, query, frag))
         req = urllib2.Request(url)
         base64string = base64.encodestring(auth)[:-1]
         basic = "Basic " + base64string
         req.add_header("Authorization", basic)
     else:
         req = urllib2.Request(url)
     url_obj = urllib2.urlopen(req)
     with open(tmp_path, 'wb') as fp:
         fp.write(url_obj.read())
     return tmp_path, url_obj.info()
开发者ID:NextThought,项目名称:buildout,代码行数:17,代码来源:download.py


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