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

Python urllib.urllib_quote函数代码示例

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

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



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

示例1: get_current_url

def get_current_url(environ, root_only=False, strip_querystring=False,
                    host_only=False):
    """A handy helper function that recreates the full URL for the current
    request or parts of it.  Here an example:

    >>> from werkzeug import create_environ
    >>> env = create_environ("/?param=foo", "http://localhost/script")
    >>> get_current_url(env)
    'http://localhost/script/?param=foo'
    >>> get_current_url(env, root_only=True)
    'http://localhost/script/'
    >>> get_current_url(env, host_only=True)
    'http://localhost/'
    >>> get_current_url(env, strip_querystring=True)
    'http://localhost/script/'

    :param environ: the WSGI environment to get the current URL from.
    :param root_only: set `True` if you only want the root URL.
    :param strip_querystring: set to `True` if you don't want the querystring.
    :param host_only: set to `True` if the host URL should be returned.
    """
    tmp = [environ['wsgi.url_scheme'], '://', get_host(environ)]
    cat = tmp.append
    if host_only:
        return ''.join(tmp) + '/'
    cat(urllib_quote(environ.get('SCRIPT_NAME', '').rstrip('/')))
    if root_only:
        cat('/')
    else:
        cat(urllib_quote('/' + environ.get('PATH_INFO', '').lstrip('/')))
        if not strip_querystring:
            qs = environ.get('QUERY_STRING')
            if qs:
                cat('?' + qs)
    return ''.join(tmp)
开发者ID:raffstah,项目名称:raven,代码行数:35,代码来源:wsgi.py


示例2: get_emailage_url

def get_emailage_url(method, url, consumer_key, consumer_secret, query=None):
    """Generate the oauth url for emailAge
    :param query:
    :param method:
    :param url:
    :param consumer_key:
    :param consumer_secret:
    :return:
    """
    if not method:
        method = "GET"

    nonce, timestamp = generate_nonce_timestamp()

    # URL encode credential params
    cred_params = [('format', 'json'), ('oauth_consumer_key', consumer_key), ('oauth_nonce', nonce),
                   ('oauth_signature_method', 'HMAC-SHA1'), ('oauth_timestamp', timestamp), ('oauth_version', '1.0')]
    if method == 'GET':
        cred_params.append(('query', query))
    cred_params = urllib_urlencode(cred_params)
    """ivar: credential parameters required in the payload."""

    query_str = cred_params

    sig_url = method.upper() + "&" + urllib_quote(url, "") + "&" + urllib_quote(query_str, "")

    sig = get_signature(consumer_secret, sig_url)
    """ivar: signature based on consumer secret to validate request."""

    oauth_url = url + "?" + query_str + "&oauth_signature=" + urllib_quote(sig.decode(), "")

    return oauth_url
开发者ID:radzhome,项目名称:python-emailage,代码行数:32,代码来源:api.py


示例3: quote

def quote(value, safe='/'):
    """
    Patched version of urllib.quote that encodes utf-8 strings before quoting
    """
    if isinstance(value, unicode):
        value = value.encode('utf-8')
    return urllib_quote(value, safe)
开发者ID:CloudVPS,项目名称:better-staticweb,代码行数:7,代码来源:better_staticweb.py


示例4: search

    def search(self, word):
        url = "searchPoints/" + urllib_quote(word)
        req = API._rest_req(url)
        req = json.loads(req.text)

        ret = [Point(i) for i in req["list"]]
        return ret
开发者ID:Gawen,项目名称:parikstra,代码行数:7,代码来源:parikstra.py


示例5: escape_shield_query

def escape_shield_query(text):
    """Escape text to be inserted in a shield API request."""
    text = urllib_quote(text, safe=' ')
    text = text.replace('_', '__')
    text = text.replace(' ', '_')
    text = text.replace('-', '--')
    return text
开发者ID:coldfix,项目名称:pypipins,代码行数:7,代码来源:shields.py


示例6: post_message_as_slackbot

def post_message_as_slackbot(team, token, channel, message):
    url = 'https://{team}.slack.com/services/hooks/slackbot'
    url += '?token={token}&channel={channel}'
    url = url.format(team=team, token=token, channel=urllib_quote(channel))
    res = requests.post(url, message)
    if res.status_code != 200:
        raise SlackerCliError("{0}:'{1}'".format(res.content, url))
开发者ID:erchn,项目名称:slacker-cli,代码行数:7,代码来源:__init__.py


示例7: _quote_query

def _quote_query(query):
    """Turn a dictionary into a query string in a URL, with keys
    in alphabetical order."""
    return "&".join("%s=%s" % (
        k, urllib_quote(
            unicode(query[k]).encode('utf-8'), safe='~'))
            for k in sorted(query))
开发者ID:patrickdessalle,项目名称:bottlenose,代码行数:7,代码来源:api.py


示例8: encode_for_api

    def encode_for_api(self, string_to_encode):
        """Make sure the URI in correctly encoded.

        Runabove api need to encode "/" to %2F because slash
        are used into URI to distinct two ressources.

        :param string_to_encode: original string_to_encode
        """
        return urllib_quote(string_to_encode).replace('/', '%2f')
开发者ID:Rbeuque74,项目名称:python-runabove,代码行数:9,代码来源:wrapper_api.py


示例9: create

    def create(self, name):
        url = BASE_URL + '/folders'

        # Clean up name
        name = name.replace(' ', '_')
        name = urllib_quote(name)
        params = {'name' : name}

        headers = {'Content-Type' : 'application/vnd.mendeley-folder.1+json'}

        return self.parent.make_post_request(url, models.Folder, params, headers=headers)
开发者ID:gitter-badger,项目名称:mendeley_python,代码行数:11,代码来源:api.py


示例10: _download_and_verify_file_name

 def _download_and_verify_file_name(self, test_file_name):
     for file_type in FILE_TYPE_MIME_TABLE.keys():
         url_encoded_file_name = urllib_quote(test_file_name)
         response = self.app.get(
             '/download/%s/%s' % (url_encoded_file_name, file_type))
         eq_(response.content_type,
             FILE_TYPE_MIME_TABLE[file_type])
         expected = (
             "attachment; filename=%s.%s;filename*=utf-8''%s.%s"
             % (url_encoded_file_name, file_type,
                url_encoded_file_name, file_type))
         eq_(response.content_disposition, expected)
开发者ID:pyexcel,项目名称:pyramid-excel,代码行数:12,代码来源:test_upload_n_download_excel.py


示例11: _get_patch

    def _get_patch(self, request, *args, **kwargs):
        try:
            resources.review_request.get_object(request, *args, **kwargs)
            filediff = self.get_object(request, *args, **kwargs)
        except ObjectDoesNotExist:
            return DOES_NOT_EXIST

        resp = HttpResponse(filediff.diff, mimetype='text/x-patch')
        filename = '%s.patch' % urllib_quote(filediff.source_file)
        resp['Content-Disposition'] = 'inline; filename=%s' % filename
        set_last_modified(resp, filediff.diffset.timestamp)

        return resp
开发者ID:romko-hr,项目名称:reviewboard,代码行数:13,代码来源:filediff.py


示例12: _make_response

def _make_response(content, content_type, status, file_name=None):
    """
    Custom response function that is called by pyexcel-webio
    """
    response = Response(content, content_type=content_type, status=status)
    if file_name:
        if PY2_VERSION and isinstance(file_name, unicode):
            file_name = file_name.encode('utf-8')
        url_encoded_file_name = urllib_quote(file_name)
        response.content_disposition = (
            "attachment; filename=%s;filename*=utf-8''%s"
            % (url_encoded_file_name, url_encoded_file_name)
        )
    return response
开发者ID:pyexcel,项目名称:pyramid-excel,代码行数:14,代码来源:__init__.py


示例13: urlencode

    def urlencode(cls, value):
        if type(value) not in (str, bytes):
            value = str(value)

        out = ""
        for char in value:
            if type(char) is int:
                char = bytearray([char])
            quoted = urllib_quote(char, safe='')
            out += quoted if quoted[0] != '%' else quoted.lower()

        return out \
            .replace('-', '%2d') \
            .replace('_', '%5f') \
            .replace('~', '%7e')
开发者ID:tgalal,项目名称:yowsup,代码行数:15,代码来源:warequest.py


示例14: get

    def get(self, request, diffset_id=None, *args, **kwargs):
        """Returns the patched file.

        The file is returned as :mimetype:`text/plain` and is the result
        of applying the patch to the original file.
        """
        try:
            attached_diffset = DiffSet.objects.filter(pk=diffset_id,
                                                      history__isnull=True)

            if attached_diffset.exists():
                filediff_resource = resources.filediff
            else:
                filediff_resource = resources.draft_filediff

            filediff = filediff_resource.get_object(
                request, diffset=diffset_id, *args, **kwargs)
        except ObjectDoesNotExist:
            return DOES_NOT_EXIST

        if filediff.deleted:
            return DOES_NOT_EXIST

        try:
            orig_file = get_original_file(filediff, request=request)
        except Exception as e:
            logging.error("Error retrieving original file: %s", e, exc_info=1,
                          request=request)
            return FILE_RETRIEVAL_ERROR

        try:
            patched_file = get_patched_file(orig_file, filediff,
                                            request=request)
        except Exception as e:
            logging.error("Error retrieving patched file: %s", e, exc_info=1,
                          request=request)
            return FILE_RETRIEVAL_ERROR

        resp = HttpResponse(patched_file, mimetype='text/plain')
        filename = urllib_quote(filediff.dest_file)
        resp['Content-Disposition'] = 'inline; filename=%s' % filename
        set_last_modified(resp, filediff.diffset.timestamp)

        return resp
开发者ID:prodigeni,项目名称:reviewboard,代码行数:44,代码来源:patched_file.py


示例15: search

	def search(self,callback,searchkey,_page=1,_per_page=30):
		"""wct.search.webcams

			Search the webcams by the given query.


			Arguments

			devid (required)
			Your developer ID. If you do not have one, please signup for a developer ID.
			query (required)
			The query to search for.
			per_page (optional)
			Number of comments to return per page. If this argument is omitted, it defaults to 10. The maximum allowed value is 50.
			page (optional)
			The page of results to return. If this argument is omitted, it defaults to 1.
		"""
		cb = lambda raw: self.searchCB(raw,callback)
		self.get("wct.search.webcams",cb,None,query=urllib_quote(searchkey),page=_page,per_page=_per_page)
开发者ID:68foxboris,项目名称:enigma2-plugins,代码行数:19,代码来源:WebcamTravel.py


示例16: link_file

    def link_file(self, file, params, file_url=None):
        """

        Parameters
        ----------
        file : dict
            Of form {'file' : Buffered Reader for file}
            The buffered reader was made by opening the pdf using open().
        params : dict
            Includes the following:
            'title' = paper title
            'id' = ID of the document to which
            the file will be attached
            (optional) '_return_type': return type of API.make_post_request
            (json, object, raw, or response)

        Returns
        -------
        Object specified by params['_return_type'].
            Generally models.LinkedFile object

        """
        base_url = 'https://api.mendeley.com'
        url = base_url + '/files'

        # Extract info from params
        title = params['title']
        doc_id = params['id']
        object_fh = models.File

        # Get rid of spaces in filename
        filename = urllib_quote(title) + '.pdf'
        filename = filename.replace('/', '%2F')

        headers = dict()
        headers['Content-Type'] = 'application/pdf'
        headers['Content-Disposition'] = 'attachment; filename=%s' % filename
        headers['Link'] = '<' + base_url + '/documents/' + doc_id + '>; rel="document"'

        API.make_post_request(API(), url, object_fh, params, headers=headers, files=file)
开发者ID:gitter-badger,项目名称:mendeley_python,代码行数:40,代码来源:api.py


示例17: quote

def quote(value, safe='/'):
    """
    Patched version of urllib.quote that encodes utf-8 strings before quoting
    """
    return urllib_quote(ensure_utf8_bytes(value), safe)
开发者ID:corystone,项目名称:swift,代码行数:5,代码来源:staticweb.py


示例18: encode_request_string

def encode_request_string(station):
    station_url = station.encode("latin-1")
    station_url = urllib_quote(station_url)
    return station_url.lower()
开发者ID:alexsavio,项目名称:mvg-cli,代码行数:4,代码来源:mvg.py


示例19: __init__

    def __init__(self, ref_tags, ref_id):

        """

        Parameters:
        -----------
        ref_tags: bs4.element.Tag
            Html tags as soup of the reference. Information provided is that
            needed in order to form a citation for the given reference.
        ref_id: int
            The id of the reference as ordered in the citing entry. A value
            of 1 indicates that this object is the first reference in the bibliography.


        """

        # Reference Bibliography Section:
        #--------------------------------
        self.ref_id = ref_id + 1 # Input is 0 indexed
        self.title = findValue(ref_tags, 'span', 'articleTitle', 'class')
        authorlist = ref_tags.find_all('span', 'author', 'class')
        self.authors = [x.text for x in authorlist]

        # Note: we can also get individual authors if we would like.
        #
        # On Wiley, each reference author is given a separate <span> tag with the class 'author'
        # so individual authors can be extracted
        #

        self.publication = findValue(ref_tags, 'span', 'journalTitle', 'class')
        self.volume = findValue(ref_tags, 'span', 'vol', 'class')
        self.date = findValue(ref_tags, 'span', 'pubYear', 'class')

        firstp = findValue(ref_tags, 'span', 'pageFirst', 'class')
        lastp = findValue(ref_tags, 'span', 'pageLast', 'class')
        if (firstp is not None) and (lastp is not None):
            self.pages = firstp + '-' + lastp
        else:
            self.pages = None


        # Reference Meta Section:
        #------------------------------

        self.crossref = None
        self.pubmed = None
        self.pubmed_id = None
        self.doi = None
        self.citetimes = None
        self.cas = None
        self.abstract = None
        self.pdf_link = None
        self.ref_references = None

        # External links (i.e. PubMed, CrossRef, CAS) are kept in a ul tag
        # Internal links (i.e. direct to abstract, references, etc.) are in a div
        # Need to check for both
        links = ref_tags.find('ul', 'externalReferences', 'class')
        if links is None:
            links = ref_tags.find('div', 'internalReferences', 'class')

        # Only proceed if either internal or external references were found
        if links is not None:
            links = links.find_all('li')

            # Check against all possible link options and save links.
            # href links are appended onto base URL ('http://onlinelibrary.wiley.com')
            #
            for link in links:
                label = link.text.lower()
                href = link.find('a', href=True)['href']
                href = urllib_quote(href)

                if 'crossref' in label:
                    self.doi = href[href.find('10.'):] # Grab everything starting with '10.' in link
                    if self.doi == -1:
                        self.doi = None
                    self.doi = urllib_unquote(self.doi)
                    # CrossRef link is in the form of _WY_URL/resolve/reference/XREF?id=10.#######
                    self.crossref = _WY_URL + urllib_unquote(href)
                elif 'pubmed' in label:
                    self.pubmed_id = re.search('[^id=]+$',href).group(0)[1:] # the [1:] is to get rid of leading '='
                    self.pubmed_id = urllib_unquote(self.pubmed_id)
                    self.pubmed = _WY_URL + urllib_unquote(href)
                elif 'web ' in label:
                    self.citetimes = re.search('[^: ]+$',label).group(0)
                elif label in ('cas', 'cas,'):
                    self.cas = _WY_URL + urllib_unquote(href)
                elif 'abstract' in label:
                    self.abstract = _WY_URL + urllib_unquote(href)
                elif 'pdf' in label:
                    self.pdf_link = _WY_URL + urllib_unquote(href)
                elif 'references' in label:
                    self.ref_references = _WY_URL + urllib_unquote(href)
开发者ID:gitter-badger,项目名称:pypub,代码行数:94,代码来源:wiley.py


示例20: quote

def quote(value):
    return urllib_quote(value.encode('utf-8'))
开发者ID:uw-it-aca,项目名称:sqlshare,代码行数:2,代码来源:dao.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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