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

Python urllib.FancyURLopener类代码示例

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

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



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

示例1: unicode_urlopen

def unicode_urlopen(url, accept_lang=None):
    """Returns a *Unicode* file-like object for non-local documents.
    Client must ensure that the URL points to non-binary data. Pass in
    an Accept-Language value to configure the FancyURLopener we
    use."""

    opener = FancyURLopener()

    if accept_lang:
        opener.addheader("Accept-Language", accept_lang)

    # We want to convert the bytes file-like object returned by
    # urllib, which is bytes in both Python 2 and Python 3
    # fortunately, and turn it into a Unicode file-like object
    # with a little help from our StringIO friend.
    page = opener.open(url)
    encoding = page.headers['content-type']
    encoding = encoding.split('charset=')
    if len(encoding) > 1:
        encoding = encoding[-1]
        page = page.read().decode(encoding)
    else:
        page = page.read()
        encoding = meta_encoding(page) or 'utf8'
        page = page.decode(encoding)

    page = StringIO(page)
    return page
开发者ID:Mekyi,项目名称:crunchy,代码行数:28,代码来源:utilities.py


示例2: __init__

	def __init__(self):
		try:
			context = ssl._create_unverified_context()
		except AttributeError:
			context = None

		FancyURLopener.__init__(self, context=context)
开发者ID:matevzv,项目名称:vesna-alh-tools,代码行数:7,代码来源:__init__.py


示例3: POST

    def POST(self):
        # disable nginx buffering
        web.header('X-Accel-Buffering', 'no')

        i = web.input(fast=False)
        #get app config if not exist will create it
        servers = get_servers(i.app_name)
        if not servers:
            servers = ['deploy']
            save_app_option(i.app_name, 'deploy_servers', 'deploy')

        yield "%d:%s" % (logging.INFO, render_ok("Application allowed to deploy those servers"))
        yield "%d:%s" % (logging.INFO, render_ok(','.join(servers)))
        servers = escape_servers(servers)

        result = {}
        data = {'app_name': i.app_name, 'app_url': i.app_url}
        for server in servers:
            url = SUFFIX % server
            try:
                opener = FancyURLopener()
                f = opener.open(url, urlencode(data))
                line = ''  # to avoid NameError for line if f has no output at all.
                for line in iter(f.readline, ''):
                    logger.info(line)
                    yield line
                if not any(word in line for word in ['succeeded', 'failed']):
                    result[server] = 'Failed'
                else:
                    result[server] = 'Succeeded'
            except Exception, e:
                yield "%d:%s" % (logging.ERROR, render_err(str(e)))
                result[server] = 'Failed'
开发者ID:xiaomen,项目名称:deploy,代码行数:33,代码来源:deploy.py


示例4: get

 def get(self, url, headers=None):
     o = FancyURLopener()
     if headers:
         for k, v in headers.items():
             o.addheader(k, v)
     self.req = o.open(url)
     return self
开发者ID:cowlicks,项目名称:rio,代码行数:7,代码来源:streamer.py


示例5: ensureFileLocal

    def ensureFileLocal(self, inFilePathOrURL):
        '''
        Takes a file path or URL. Sets self.localFilePath
        to the same path if file is local, or
        if the file is remote but uncompressed. 
        If a file is remote and compressed, retrieves
        the file into a local tmp file and returns that
        file name. In this case the flag self.deleteTempFile
        is set to True. 

        :param inFilePathOrURL: file path or URL to file
        :type inFilePathOrURL: String
        '''
        self.localFilePath = inFilePathOrURL
        self.deleteTempFile = False
        if self.compression == COMPRESSION_TYPE.NO_COMPRESSION:
            return
        # Got compressed file; is it local?
        parseResult = urlparse(inFilePathOrURL)
        if parseResult.scheme == 'file':
            self.localFilePath = parseResult.path
            return
        opener = FancyURLopener()
        # Throws IOError if URL does not exist:
        self.localFilePath = opener.retrieve(inFilePathOrURL)[0]
        self.deleteTempFile = True
开发者ID:paepcke,项目名称:json_to_relation,代码行数:26,代码来源:input_source.py


示例6: getNaturalRandom

 def getNaturalRandom(self, min=1, max=49, nbNumbers=6):
     unique = False
     while not unique:
         url_opener = FancyURLopener()
         data = url_opener.open("http://www.random.org/integers/?num=%s&min=%s&max=%s&col=%s&base=10&format=plain&rnd=new" % (nbNumbers, min, max, nbNumbers))
         randList = data.readlines()[0].rstrip('\n').split('\t')
         unique = bool(len(randList) == len(list(set(randList))))
     return sorted([int(i) for i in randList])
开发者ID:alok1974,项目名称:lottoGenerator,代码行数:8,代码来源:randomGenerator.py


示例7: utOpen

def utOpen(file):
    # Open file
    if 'http' in file:
        opener = FancyURLopener()
        f = opener.open(file)
    else:
        f = open(file,'rb+')
    return f
开发者ID:eaudeweb,项目名称:naaya,代码行数:8,代码来源:utils.py


示例8: utRead

def utRead(file):
    """ Open file on local or remote system. """
    if 'http' in file:
        opener = FancyURLopener()
        f = opener.open(file)
    else:
        f = open(file,'rb+')
    return f
开发者ID:eea,项目名称:Products.Reportek,代码行数:8,代码来源:RepUtils.py


示例9: http_error_default

 def http_error_default(self, url, fp, errcode, errmsg, headers):
     if errcode == 404:
         raise urllib2.HTTPError(url, errcode, errmsg, headers, fp)
     else:
         FancyURLopener.http_error_default(
             url,
             fp,
             errcode,
             errmsg,
             headers)
开发者ID:pombredanne,项目名称:pdbparse-1,代码行数:10,代码来源:symchk.py


示例10: __load_photo_page

	def __load_photo_page(self, photo_id):
		opener = FancyURLopener()
		res = None
		body = None
		link = photo_page_template % photo_id

		try:
			res = opener.open(link)
			body = res.read()
		except IOError, error:
			print "[!] {0}".format(error.strerror)
开发者ID:x-cray,项目名称:votingstats,代码行数:11,代码来源:parse.py


示例11: fill_hot_cache

    def fill_hot_cache( self ):
        bases   = [ 'a', 'g', 'c', 't' ]
        url = self.url + urlencode( self.query )
        url_opener = FancyURLopener( )
        fh = url_opener.open( url )
        hot_rand_handle = SGMLExtractorHandle( fh, [ 'pre', ] )

        hot_cache = fh.read()
        self.hot_cache = hot_cache
        fh.close()
        return self.hot_cache
开发者ID:dbmi-pitt,项目名称:DIKB-Evidence-analytics,代码行数:11,代码来源:HotRand.py


示例12: __init__

 def __init__(self, *args, **kwargs):
     self._last_url = u''
     FancyURLopener.__init__(self, *args, **kwargs)
     # Headers to add to every request.
     # XXX: IMDb's web server doesn't like urllib-based programs,
     #      so lets fake to be Mozilla.
     #      Wow!  I'm shocked by my total lack of ethic! <g>
     self.set_header('User-agent', 'Mozilla/5.0')
     # XXX: This class is used also to perform "Exact Primary
     #      [Title|Name]" searches, and so by default the cookie is set.
     c_header = 'id=%s; uu=%s' % (_cookie_id, _cookie_uu)
     self.set_header('Cookie', c_header)
开发者ID:conwetlab,项目名称:ezweb-gadgets,代码行数:12,代码来源:__init__.py


示例13: download

	def download (self, download_dir):
		result = path.join (download_dir, self.package_basename)
		if path.exists (result):
			print 'Found install', self.package_basename
		else:
			dir_util.mkpath (download_dir)
			url = "http://www.eiffel-loop.com/download/" + self.package_basename
			print 'Downloading:', url
	
			web = FancyURLopener ()
			web.retrieve (url, result, display_progress)

		return result
开发者ID:finnianr,项目名称:Eiffel-Loop,代码行数:13,代码来源:package.py


示例14: __init__

    def __init__(self, ftpproxy=''):
        """RebaseUpdate([ftpproxy]]) -> new RebaseUpdate instance.

        if ftpproxy is not given RebaseUpdate uses the corresponding
        variable from RanaConfig.

        ftpproxy is the proxy to use if any.
        """
        proxy = {'ftp': ftpproxy or ftp_proxy}
        if not Rebase_name:
            raise FtpNameError('Rebase')
        if not proxy['ftp']:
            proxy = {}
        FancyURLopener.__init__(self, proxy)
开发者ID:Benjamin-Lee,项目名称:biopython,代码行数:14,代码来源:rebase_update.py


示例15: __init__

 def __init__(self, *args, **kwargs):
     self._last_url = u""
     FancyURLopener.__init__(self, *args, **kwargs)
     # Headers to add to every request.
     # XXX: IMDb's web server doesn't like urllib-based programs,
     #      so lets fake to be Mozilla.
     #      Wow!  I'm shocked by my total lack of ethic! <g>
     for header in ("User-Agent", "User-agent", "user-agent"):
         self.del_header(header)
     self.set_header("User-Agent", "Mozilla/5.0")
     self.set_header("Accept-Language", "en-us,en;q=0.5")
     # XXX: This class is used also to perform "Exact Primary
     #      [Title|Name]" searches, and so by default the cookie is set.
     c_header = "uu=%s; id=%s" % (_cookie_uu, _cookie_id)
     self.set_header("Cookie", c_header)
开发者ID:Rickol91,项目名称:SickRage,代码行数:15,代码来源:__init__.py


示例16: __init__

    def __init__(self, e_mail="", ftpproxy=""):
        """RebaseUpdate([e_mail[, ftpproxy]]) -> new RebaseUpdate instance.

        if e_mail and ftpproxy are not given RebaseUpdate uses the corresponding
        variable from RanaConfig.

        e_mail is the password for the anonymous ftp connection to Rebase.
        ftpproxy is the proxy to use if any."""
        proxy = {"ftp": ftpproxy or ftp_proxy}
        global Rebase_password
        Rebase_password = e_mail or Rebase_password
        if not Rebase_password:
            raise FtpPasswordError("Rebase")
        if not Rebase_name:
            raise FtpNameError("Rebase")
        FancyURLopener.__init__(self, proxy)
开发者ID:kaspermunch,项目名称:sap,代码行数:16,代码来源:Update.py


示例17: deploy_to_server

def deploy_to_server(data, server):
    opener = FancyURLopener()
    f = opener.open(server, urlencode(data))
    line = ''  # to avoid NameError for line if f has no output at all.
    for line in iter(f.readline, ''):
        try:
            loglevel, line = line.split(':', 1)
            loglevel = int(loglevel)
        except ValueError:
            loglevel = logging.DEBUG
        logger.log(loglevel, "%s", line.rstrip())

    if not any(word in line for word in ['succeeded', 'failed']):
        return 'Failed'
    else:
        return 'Succeeded'
开发者ID:pigsoldierlu,项目名称:sheep,代码行数:16,代码来源:deploy.py


示例18: __init__

    def __init__(self, *args, **kwargs):
        try: self.username = kwargs['username']
        except KeyError: self.username = None
        try: self.password = kwargs['password']
        except KeyError: self.password = None

        # once urllib uses new style classes, or in python 3.0+, use:
        # super(FancyURLopenerMod, self).__init__(*args, **kwargs)
        # till then this will work, but not in python 3.0+:
        FancyURLopener.__init__(self, *args, **kwargs)

        # only try opening the account once
        #self.authtries = 0
        #self.maxauthtries = 3

        self.flag = False
开发者ID:hrangan,项目名称:gmail.py,代码行数:16,代码来源:gmail.py


示例19: download_ims_image

def download_ims_image(imsresp):
    inputfilepath = imsresp.getUrl()
    is_via_http = 0
    if 'http' in inputfilepath:
        opener = FancyURLopener()
        is_via_http = 1
        l_file = inputfilepath
        l_filename = l_file.split('/')[-1]
        l_data = opener.open(l_file).read()
        l_file = open(join(FILES_PATH, l_filename), 'wb')
        l_file.write(l_data)
        l_file.close()
        l_temploc = inputfilepath.split('/')[-1]
        inputfilepath = join(FILES_PATH, l_temploc)
    imsresp.setUrl(inputfilepath)
    return imsresp
开发者ID:anton16,项目名称:reportek-converters,代码行数:16,代码来源:gml_image.py


示例20: check_news

def check_news(db_conn):
    """
    check_news :: Sqlite3ConnectionData -> Void

    Takes an open Sqlite3 connection
    Checks the Archlinux.org news and prints it if it's new
    """
    br = FancyURLopener()
    response = br.open("http://www.archlinux.org/news/").readlines()
    for a in response:
        if 'title="View: ' in a:
            news = re.findall('">([^<]+)</a>', a)[0]
            break
    if sqlite_manager.is_news_new(db_conn, news):
            sqlite_manager.replace_news(db_conn, news)
            print news
开发者ID:venam,项目名称:updater_v2,代码行数:16,代码来源:archnews.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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