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

Python compat.urlparse函数代码示例

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

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



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

示例1: test_setup_requires_honors_fetch_params

 def test_setup_requires_honors_fetch_params(self):
     """
     When easy_install installs a source distribution which specifies
     setup_requires, it should honor the fetch parameters (such as
     allow-hosts, index-url, and find-links).
     """
     # set up a server which will simulate an alternate package index.
     p_index = setuptools.tests.server.MockServer()
     p_index.start()
     netloc = 1
     p_index_loc = urlparse(p_index.url)[netloc]
     if p_index_loc.endswith(':0'):
         # Some platforms (Jython) don't find a port to which to bind,
         #  so skip this test for them.
         return
     with quiet_context():
         # create an sdist that has a build-time dependency.
         with TestSetupRequires.create_sdist() as dist_file:
             with tempdir_context() as temp_install_dir:
                 with environment_context(PYTHONPATH=temp_install_dir):
                     ei_params = ['--index-url', p_index.url,
                         '--allow-hosts', p_index_loc,
                         '--exclude-scripts', '--install-dir', temp_install_dir,
                         dist_file]
                     with reset_setup_stop_context():
                         with argv_context(['easy_install']):
                             # attempt to install the dist. It should fail because
                             #  it doesn't exist.
                             self.assertRaises(SystemExit,
                                 easy_install_pkg.main, ei_params)
     # there should have been two or three requests to the server
     #  (three happens on Python 3.3a)
     self.assertTrue(2 <= len(p_index.requests) <= 3)
     self.assertEqual(p_index.requests[0].path, '/does-not-exist/')
开发者ID:13lcp2000,项目名称:recetario4-4,代码行数:34,代码来源:test_easy_install.py


示例2: local_open

def local_open(url):
    """Read a local path, with special support for directories"""
    scheme, server, path, param, query, frag = urlparse(url)
    filename = url2pathname(path)
    if os.path.isfile(filename):
        return urllib2.urlopen(url)
    elif path.endswith('/') and os.path.isdir(filename):
        files = []
        for f in os.listdir(filename):
            filepath = os.path.join(filename, f)
            if f == 'index.html':
                with open(filepath, 'r') as fp:
                    body = fp.read()
                break
            elif os.path.isdir(filepath):
                f += '/'
            files.append('<a href="{name}">{name}</a>'.format(name=f))
        else:
            tmpl = ("<html><head><title>{url}</title>"
                "</head><body>{files}</body></html>")
            body = tmpl.format(url=url, files='\n'.join(files))
        status, message = 200, "OK"
    else:
        status, message, body = 404, "Path not found", "Not found"

    headers = {'content-type': 'text/html'}
    return HTTPError(url, status, message, headers, StringIO(body))
开发者ID:zyh199552,项目名称:sysu-spider,代码行数:27,代码来源:package_index.py


示例3: url_ok

 def url_ok(self, url, fatal=False):
     s = URL_SCHEME(url)
     if (s and s.group(1).lower()=='file') or self.allows(urlparse(url)[1]):
         return True
     msg = "\nLink to % s ***BLOCKED*** by --allow-hosts\n"
     if fatal:
         raise DistutilsError(msg % url)
     else:
         self.warn(msg, url)
开发者ID:ioram7,项目名称:keystone-federado-pgid2013,代码行数:9,代码来源:package_index.py


示例4: test_setup_requires_honors_fetch_params

    def test_setup_requires_honors_fetch_params(self):
        """
        When easy_install installs a source distribution which specifies
        setup_requires, it should honor the fetch parameters (such as
        allow-hosts, index-url, and find-links).
        """
        # set up a server which will simulate an alternate package index.
        p_index = setuptools.tests.server.MockServer()
        p_index.start()
        netloc = 1
        p_index_loc = urlparse(p_index.url)[netloc]
        if p_index_loc.endswith(':0'):
            # Some platforms (Jython) don't find a port to which to bind,
            #  so skip this test for them.
            return

        # I realize this is all-but-impossible to read, because it was
        #  ported from some well-factored, safe code using 'with'. If you
        #  need to maintain this code, consider making the changes in
        #  the parent revision (of this comment) and then port the changes
        #  back for Python 2.4 (or deprecate Python 2.4).

        def install(dist_file):
            def install_at(temp_install_dir):
                def install_env():
                    ei_params = ['--index-url', p_index.url,
                        '--allow-hosts', p_index_loc,
                        '--exclude-scripts', '--install-dir', temp_install_dir,
                        dist_file]
                    def install_clean_reset():
                        def install_clean_argv():
                            # attempt to install the dist. It should fail because
                            #  it doesn't exist.
                            self.assertRaises(SystemExit,
                                easy_install_pkg.main, ei_params)
                        argv_context(install_clean_argv, ['easy_install'])
                    reset_setup_stop_context(install_clean_reset)
                environment_context(install_env, PYTHONPATH=temp_install_dir)
            tempdir_context(install_at)

        # create an sdist that has a build-time dependency.
        self.create_sdist(install)

        # there should have been two or three requests to the server
        #  (three happens on Python 3.3a)
        self.assertTrue(2 <= len(p_index.requests) <= 3)
        self.assertEqual(p_index.requests[0].path, '/does-not-exist/')
开发者ID:31415us,项目名称:trajectory,代码行数:47,代码来源:test_easy_install.py


示例5: upload_file

    def upload_file(self, filename):
        f = open(filename, 'rb')
        content = f.read()
        f.close()
        meta = self.distribution.metadata
        data = {
            ':action': 'doc_upload',
            'name': meta.get_name(),
            'content': (os.path.basename(filename), content),
        }
        # set up the authentication
        credentials = b(self.username + ':' + self.password)
        credentials = standard_b64encode(credentials)
        if PY3:
            credentials = credentials.decode('ascii')
        auth = "Basic " + credentials

        # Build up the MIME payload for the POST data
        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
        sep_boundary = b('\n--') + b(boundary)
        end_boundary = sep_boundary + b('--')
        body = []
        for key, values in iteritems(data):
            title = '\nContent-Disposition: form-data; name="%s"' % key
            # handle multiple entries for the same name
            if not isinstance(values, list):
                values = [values]
            for value in values:
                if type(value) is tuple:
                    title += '; filename="%s"' % value[0]
                    value = value[1]
                else:
                    value = b(value)
                body.append(sep_boundary)
                body.append(b(title))
                body.append(b("\n\n"))
                body.append(value)
                if value and value[-1:] == b('\r'):
                    body.append(b('\n'))  # write an extra newline (lurve Macs)
        body.append(end_boundary)
        body.append(b("\n"))
        body = b('').join(body)

        self.announce("Submitting documentation to %s" % (self.repository),
                      log.INFO)

        # build the Request
        # We can't use urllib2 since we need to send the Basic
        # auth right with the first request
        schema, netloc, url, params, query, fragments = \
            urlparse(self.repository)
        assert not params and not query and not fragments
        if schema == 'http':
            conn = httplib.HTTPConnection(netloc)
        elif schema == 'https':
            conn = httplib.HTTPSConnection(netloc)
        else:
            raise AssertionError("unsupported schema " + schema)

        data = ''
        try:
            conn.connect()
            conn.putrequest("POST", url)
            content_type = 'multipart/form-data; boundary=%s' % boundary
            conn.putheader('Content-type', content_type)
            conn.putheader('Content-length', str(len(body)))
            conn.putheader('Authorization', auth)
            conn.endheaders()
            conn.send(body)
        except socket.error:
            e = sys.exc_info()[1]
            self.announce(str(e), log.ERROR)
            return

        r = conn.getresponse()
        if r.status == 200:
            self.announce('Server response (%s): %s' % (r.status, r.reason),
                          log.INFO)
        elif r.status == 301:
            location = r.getheader('Location')
            if location is None:
                location = 'https://pythonhosted.org/%s/' % meta.get_name()
            self.announce('Upload successful. Visit %s' % location,
                          log.INFO)
        else:
            self.announce('Upload failed (%s): %s' % (r.status, r.reason),
                          log.ERROR)
        if self.show_response:
            print('-' * 75, r.read(), '-' * 75)
开发者ID:0x,项目名称:kivi-tests,代码行数:89,代码来源:upload_docs.py


示例6: b

                body.append(value)
                if value and value[-1:] == b('\r'):
                    body.append(b('\n'))  # write an extra newline (lurve Macs)
        body.append(end_boundary)
        body.append(b("\n"))
        body = b('').join(body)

        self.announce("Submitting documentation to %s" % (self.repository),
                      log.INFO)

        # build the Request
        # We can't use urllib2 since we need to send the Basic
        # auth right with the first request
        schema, netloc, url, params, query, fragments = \
<<<<<<< HEAD
            urlparse(self.repository)
        assert not params and not query and not fragments
        if schema == 'http':
            conn = httplib.HTTPConnection(netloc)
        elif schema == 'https':
            conn = httplib.HTTPSConnection(netloc)
        else:
            raise AssertionError("unsupported schema "+schema)
=======
            urllib.parse.urlparse(self.repository)
        assert not params and not query and not fragments
        if schema == 'http':
            conn = http_client.HTTPConnection(netloc)
        elif schema == 'https':
            conn = http_client.HTTPSConnection(netloc)
        else:
开发者ID:Yankur,项目名称:Web-application,代码行数:31,代码来源:upload_docs.py


示例7: upload_file

    def upload_file(self, command, pyversion, filename):
        # Sign if requested
        if self.sign:
            gpg_args = ["gpg", "--detach-sign", "-a", filename]
            if self.identity:
                gpg_args[2:2] = ["--local-user", self.identity]
            spawn(gpg_args,
                  dry_run=self.dry_run)

        # Fill in the data
        f = open(filename,'rb')
        content = f.read()
        f.close()
        basename = os.path.basename(filename)
        comment = ''
        if command=='bdist_egg' and self.distribution.has_ext_modules():
            comment = "built on %s" % platform.platform(terse=1)
        data = {
            ':action':'file_upload',
            'protocol_version':'1',
            'name':self.distribution.get_name(),
            'version':self.distribution.get_version(),
            'content':(basename,content),
            'filetype':command,
            'pyversion':pyversion,
            'md5_digest':md5(content).hexdigest(),
            }
        if command == 'bdist_rpm':
            dist, version, id = platform.dist()
            if dist:
                comment = 'built for %s %s' % (dist, version)
        elif command == 'bdist_dumb':
            comment = 'built for %s' % platform.platform(terse=1)
        data['comment'] = comment

        if self.sign:
            asc_file = open(filename + ".asc")
            data['gpg_signature'] = (os.path.basename(filename) + ".asc", asc_file.read())
            asc_file.close()

        # set up the authentication
        auth = "Basic " + base64.encodestring(self.username + ":" + self.password).strip()

        # Build up the MIME payload for the POST data
        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
        sep_boundary = '\n--' + boundary
        end_boundary = sep_boundary + '--'
        body = StringIO.StringIO()
        for key, value in data.items():
            # handle multiple entries for the same name
            if type(value) != type([]):
                value = [value]
            for value in value:
                if type(value) is tuple:
                    fn = ';filename="%s"' % value[0]
                    value = value[1]
                else:
                    fn = ""
                value = str(value)
                body.write(sep_boundary)
                body.write('\nContent-Disposition: form-data; name="%s"'%key)
                body.write(fn)
                body.write("\n\n")
                body.write(value)
                if value and value[-1] == '\r':
                    body.write('\n')  # write an extra newline (lurve Macs)
        body.write(end_boundary)
        body.write("\n")
        body = body.getvalue()

        self.announce("Submitting %s to %s" % (filename, self.repository), log.INFO)

        # build the Request
        # We can't use urllib2 since we need to send the Basic
        # auth right with the first request
        schema, netloc, url, params, query, fragments = \
            urlparse(self.repository)
        assert not params and not query and not fragments
        if schema == 'http':
            http = httplib.HTTPConnection(netloc)
        elif schema == 'https':
            http = httplib.HTTPSConnection(netloc)
        else:
            raise AssertionError("unsupported schema " + schema)

        data = ''
        loglevel = log.INFO
        try:
            http.connect()
            http.putrequest("POST", url)
            http.putheader('Content-type',
                           'multipart/form-data; boundary=%s'%boundary)
            http.putheader('Content-length', str(len(body)))
            http.putheader('Authorization', auth)
            http.endheaders()
            http.send(body)
        except socket.error:
            e = sys.exc_info()[1]
            self.announce(str(e), log.ERROR)
            return
#.........这里部分代码省略.........
开发者ID:AT-GROUP,项目名称:AT-PLANNER,代码行数:101,代码来源:upload.py


示例8: open_with_auth

def open_with_auth(url, opener=urllib2.urlopen):
    """Open a urllib2 request, handling HTTP authentication"""

    scheme, netloc, path, params, query, frag = urlparse(url)
开发者ID:Yankur,项目名称:Web-application,代码行数:4,代码来源:package_index.py


示例9: egg_info_for_url

            py_ver = name[-7:-4]
            base = name[:-16]
            plat = 'win32'
        elif lower.endswith('.win-amd64.exe'):
            base = name[:-14]
            plat = 'win-amd64'
        elif lower.startswith('.win-amd64-py',-20):
            py_ver = name[-7:-4]
            base = name[:-20]
            plat = 'win-amd64'
    return base,py_ver,plat


def egg_info_for_url(url):
<<<<<<< HEAD
    scheme, server, path, parameters, query, fragment = urlparse(url)
    base = unquote(path.split('/')[-1])
    if server=='sourceforge.net' and base=='download':    # XXX Yuck
        base = unquote(path.split('/')[-2])
=======
    parts = urllib.parse.urlparse(url)
    scheme, server, path, parameters, query, fragment = parts
    base = urllib.parse.unquote(path.split('/')[-1])
    if server=='sourceforge.net' and base=='download':    # XXX Yuck
        base = urllib.parse.unquote(path.split('/')[-2])
>>>>>>> 54eef0be98b1b67c8507db91f4cfa90b64991027
    if '#' in base: base, fragment = base.split('#',1)
    return base,fragment

def distros_for_url(url, metadata=None):
    """Yield egg or source distribution objects that might be found at a URL"""
开发者ID:Yankur,项目名称:Web-application,代码行数:31,代码来源:package_index.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python compat.urlunparse函数代码示例发布时间:2022-05-27
下一篇:
Python compat.urljoin函数代码示例发布时间: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