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

Python parse.url_quote函数代码示例

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

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



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

示例1: create_link

def create_link(href, base_dir, runResult=None, href_base=None):
    def get_replacements(source_file):
        return [
            ('inputfile_name', os.path.basename(source_file)),
            ('inputfile_path', os.path.dirname(source_file) or '.'),
            ('inputfile_path_abs', os.path.dirname(os.path.abspath(source_file))),
            # The following are deprecated: do not use anymore.
            ('sourcefile_name', os.path.basename(source_file)),
            ('sourcefile_path', os.path.dirname(source_file) or '.'),
            ('sourcefile_path_abs', os.path.dirname(os.path.abspath(source_file))),
        ] + ([
            ('logfile_name',     os.path.basename(runResult.log_file)),
            ('logfile_path',     os.path.dirname(os.path.relpath(runResult.log_file, href_base or '.')) or '.'),
            ('logfile_path_abs', os.path.dirname(os.path.abspath(runResult.log_file))),
        ] if runResult.log_file else [])

    source_file = os.path.relpath(runResult.task_id[0], href_base or '.') if runResult else None

    if is_url(href):
        # quote special characters only in inserted variable values, not full URL
        if source_file:
            source_file = url_quote(source_file)
            href = benchexec.util.substitute_vars(href, get_replacements(source_file))
        return href

    # quote special characters everywhere (but not twice in source_file!)
    if source_file:
        href = benchexec.util.substitute_vars(href, get_replacements(source_file))
    return url_quote(os.path.relpath(href, base_dir))
开发者ID:martin-neuhaeusser,项目名称:benchexec,代码行数:29,代码来源:util.py


示例2: authenticate

 def authenticate(self, environ):
     """ This function takes a WSGI environment and authenticates
         the request returning authenticated user or error.
     """
     method = REQUEST_METHOD(environ)
     fullpath = url_quote(SCRIPT_NAME(environ)) + url_quote(PATH_INFO(environ))
     authorization = AUTHORIZATION(environ)
     if not authorization:
         return self.build_authentication()
     (authmeth, auth) = authorization.split(" ", 1)
     if 'digest' != authmeth.lower():
         return self.build_authentication()
     amap = dict(_auth_to_kv_pairs(auth))
     try:
         username = amap['username']
         authpath = amap['uri']
         nonce    = amap['nonce']
         realm    = amap['realm']
         response = amap['response']
         assert authpath.split("?", 1)[0] in fullpath
         assert realm == self.realm
         qop      = amap.get('qop', '')
         cnonce   = amap.get('cnonce', '')
         nc       = amap.get('nc', '00000000')
         if qop:
             assert 'auth' == qop
             assert nonce and nc
     except:
         return self.build_authentication()
     ha1 = self.authfunc(environ, realm, username)
     return self.compute(ha1, username, response, method, authpath,
                         nonce, nc, cnonce, qop)
开发者ID:terrasea,项目名称:paste,代码行数:32,代码来源:digest.py


示例3: get_forecast_data

def get_forecast_data(latitude, longitude):
    latitude, longitude = url_quote(str(latitude)), url_quote(str(longitude))
    url = 'https://api.forecast.io/forecast/{}/{},{}'.format(FORECAST_API_KEY, latitude, longitude)
    response = requests.get(url)
    if response.status_code == 200:
        return WeatherData(response.json())
    else:
        raise ValueError('Could not fetch weather forecast.', latitude, longitude, response)
开发者ID:sgrowe,项目名称:yoyo-weather,代码行数:8,代码来源:views.py


示例4: get_links

def get_links(query, no_ssl):
    if no_ssl:
        search_url = "http://" + SEARCH_URL.format(url_quote(query))
    else:
        search_url = "https://" + SEARCH_URL.format(url_quote(query))
    result = get_result(search_url)
    html = pq(result)
    return [a.attrib['href'] for a in html('.l')] or \
        [a.attrib['href'] for a in html('.r')('a')]
开发者ID:eddie-dunn,项目名称:howdoi,代码行数:9,代码来源:howdoi.py


示例5: _get_authorization

    def _get_authorization(self, request, httpclient):
        uri = self.host
        uri = url_quote(uri, '').lower()
        expiry = str(self._get_expiry())

        to_sign = uri + '\n' + expiry
        signature = url_quote(_sign_string(self.key_value, to_sign, 1))

        auth_format = 'SharedAccessSignature sig={0}&se={1}&skn={2}&sr={3}'
        auth = auth_format.format(signature, expiry, self.key_name, self.host)
        return auth
开发者ID:elastacloud,项目名称:iothackathondx,代码行数:11,代码来源:IoTHub.py


示例6: create_link

def create_link(runResult, base_dir, column):
    source_file = runResult.task_id[0]
    href = column.href or runResult.log_file

    if href.startswith("http://") or href.startswith("https://") or href.startswith("file:"):
        # quote special characters only in inserted variable values, not full URL
        source_file = url_quote(source_file)
        href = model.substitute_vars([href], None, source_file)[0]
        return href

    # quote special characters everywhere (but not twice in source_file!)
    href = model.substitute_vars([href], None, source_file)[0]
    return url_quote(os.path.relpath(href, base_dir))
开发者ID:niyasc,项目名称:benchexec-unofficial,代码行数:13,代码来源:util.py


示例7: get_links

def get_links(query):
    localization_url = LOCALIZATON_URLS[LOCALIZATION]

    pr_debug(url_quote(query))
    pr_debug(2, SEARCH_URL.format(localization_url, url_quote(query)))
    result = get_result(SEARCH_URL.format(localization_url, url_quote(query)))
    html = pq(result)
    #return [a.attrib['href'] for a in html('.l')] or \
        #[a.attrib['href'] for a in html('.r')('a')]
    for a in html('.l'):
        pr_debug("123", a.text())
    links = [a.attrib['href'] for a in html('.l')] or \
        [a.attrib['href'] for a in html('.r')('a')]

    pr_debug(' '.join(links))
    return links
开发者ID:azhe12,项目名称:quickQuery,代码行数:16,代码来源:quickQuery.py


示例8: post

 def post(self, url, recipient_public_key):
     """
     Actually send the message to an HTTP/HTTPs endpoint.
     """
     xml = url_quote(self.create_salmon_envelope(recipient_public_key))
     data = urlencode({"xml": xml})
     return urlopen(url, data.encode("ascii"))
开发者ID:Zauberstuhl,项目名称:pyaspora,代码行数:7,代码来源:protocol.py


示例9: _get_feed_episodes

	def _get_feed_episodes(self, show_key, **kwargs):
		"""
		Always returns a list.
		"""
		info("Getting episodes for Nyaa/{}".format(show_key))
		if "domain" not in self.config or not self.config["domain"]:
			error("  Domain not specified in config")
			return list()
		
		# Send request
		query = re.sub("[`[email protected]#$%^&*()+=:;,.<>?/|\\'\"]+", " ", show_key)
		query = re.sub("  ", " ", query)
		debug("  query={}".format(query))
		query = url_quote(query, safe="", errors="ignore")
		
		url = self._search_base.format(domain=self.config["domain"], q=query)
		response = self.request(url, rss=True, **kwargs)
		if response is None:
			error("Cannot get latest show for Nyaa/{}".format(show_key))
			return list()
		
		# Parse RSS feed
		if not _verify_feed(response):
			warning("Parsed feed could not be verified, may have unexpected results")
		return response.get("entries", list())
开发者ID:Indekkusu-LP,项目名称:holo,代码行数:25,代码来源:nyaa.py


示例10: _update_request

def _update_request(request):
    # Verify body
    if request.body:
        request.body = _get_data_bytes_or_stream_only('request.body', request.body)
        length = _len_plus(request.body)

        # only scenario where this case is plausible is if the stream object is not seekable.
        if length is None:
            raise ValueError(_ERROR_VALUE_SHOULD_BE_SEEKABLE_STREAM)

        # if it is PUT, POST, MERGE, DELETE, need to add content-length to header.
        if request.method in ['PUT', 'POST', 'MERGE', 'DELETE']:
            request.headers['Content-Length'] = str(length)

    # append addtional headers based on the service
    request.headers['x-ms-version'] = X_MS_VERSION
    request.headers['User-Agent'] = USER_AGENT_STRING
    request.headers['x-ms-client-request-id'] = str(uuid.uuid1())

    # If the host has a path component (ex local storage), move it
    path = request.host.split('/', 1)
    if len(path) == 2:
        request.host = path[0]
        request.path = '/{}{}'.format(path[1], request.path)

    # Encode and optionally add local storage prefix to path
    request.path = url_quote(request.path, '/()$=\',~')
开发者ID:pexip,项目名称:os-python-azure-storage,代码行数:27,代码来源:_serialization.py


示例11: get_data_url

	def get_data_url(self, max_width = None):
		data_url = b'data:{};base64,{}'
		
		if self.is_image():
			image_file = ImageBufferIO(self.file_data)
			output = ImageBufferIO()
			
			try:
				image = Image.open(image_file)
				
				s = image.size
				
				if max_width and s[0] > max_width:
					ratio = max_width / s[0]
					width = s[0] * ratio
					height = s[1] * ratio
					self._generate_thumbnail(image, output, (width, height))
					
					file_data = output.getvalue()
				else:
					file_data = image_file.getvalue()
			except IOError:
				file_data = self.file_data
				logger.exception('Error when trying to resize image for data: url')
		else:
			file_data = self.file_data
			
		data = bytes(url_quote(file_data.encode('base64')))
		
		return data_url.format(self.content_type, data)
开发者ID:AsymmetricVentures,项目名称:asymmetricbase,代码行数:30,代码来源:s3file.py


示例12: register_basic_user

def register_basic_user(request):
    """
    Register a user with username and password
    """
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])
    if request.JSON is None:
        return JsonResponse(
            {'error': 'Expected a json request'}, status=400)
    for key in ('email', 'username', 'password'):
        if key not in request.JSON:
            return JsonResponse(
                {'error': 'Required key {0} not found in body'.format(key)},
                status=400)
    username = request.JSON['username']
    try:
        user = User.objects.get_by_natural_key(User.Type.BASIC, username)
        return JsonResponse({'error': 'User already exists'},
                            status=400)
    except User.DoesNotExist:
        user = User.objects.create_basic_user(username=username,
                                              email=request.JSON['email'],
                                              password=request.JSON['password'])

    response = partial_json_response(request, USER_RESOURCE.to_json(user))
    auth_token = user.get_auth_token(request.JSON['password'])
    user = authenticate(username=username, force=True)

    response.set_cookie(
        'authToken',
        url_quote(auth_token),
        ## TODO: auth token should be http only.
        # httponly=True
    )
    return response
开发者ID:sam-server,项目名称:sam_server,代码行数:35,代码来源:views.py


示例13: show_search

def show_search(show):
    show = url_quote(show)
    url = endpoints.show_search.format(show)
    q = query_endpoint(url)
    if q:
        return q
    else:
        raise ShowNotFound(str(show) + ' not found')
开发者ID:Murodese,项目名称:pytvmaze,代码行数:8,代码来源:tvmaze.py


示例14: getBaseUrl

    def getBaseUrl(self):
        '''Return a file: URL that probably points to the basedir.

        This is used as a halfway sane default when the base URL is not
        provided; not perfect, but should work in most cases.'''
        components = util.splitpath(os.path.abspath(self.basepath))
        url = '/'.join([url_quote(component, '') for component in components])
        return 'file:///' + url + '/'
开发者ID:eyefox47,项目名称:dosage,代码行数:8,代码来源:events.py


示例15: people_search

def people_search(person):
    person = url_quote(person)
    url = endpoints.people_search.format(person)
    q = query_endpoint(url)
    if q:
        return q
    else:
        raise PersonNotFound('Couldn\'t find person: ' + str(person))
开发者ID:Murodese,项目名称:pytvmaze,代码行数:8,代码来源:tvmaze.py


示例16: get_time_entries

    def get_time_entries(self, start=None, end=None):
        """Get the list of entries for the specified time range,
        or the latest entries if no dates specified"""
        # Fetch the data or die trying.
        # Toggle has the start/end dates creating a confusing
        # backwards range. Swap them here.
        url = "%s/time_entries.json" % self.base_url
        if start is not None and end is not None:
            url = "%s?start_date=%s&end_date=%s" % \
                    (url, url_quote(str(end)), url_quote(str(start)))
        if self.verbose:
            print(url)
        r = requests.get(url, auth=self.auth)
        self._raise_if_error(r)

        if self.verbose:
            print(r.text)

        return [TogglEntry(e) for e in json.loads(r.text)['data']]
开发者ID:mthowe,项目名称:toggl-cli,代码行数:19,代码来源:libtoggl.py


示例17: hfs_quote

def hfs_quote(path):
    if isinstance(path, unicode):
        raise TypeError('bytes are required')
    try:
        path.decode('utf-8')
    except UnicodeDecodeError:
        path = url_quote(path) # Not UTF-8
        if sys.version_info >= (3,):
            path = path.encode('ascii')
    return path
开发者ID:GiantTao,项目名称:openstack-ubuntu-14-04,代码行数:10,代码来源:utils.py


示例18: test_keeps_extension_filename

    def test_keeps_extension_filename(self, api_client, storage):
        xpi = LegacyAddonFileFactory()
        res = self._upload_extension(api_client, xpi.path)
        assert res.status_code == 201, f"body of unexpected response: {res.data}"  # created
        _, filename = os.path.split(xpi.path)
        assert res.data["xpi"].split("/")[-1] == url_quote(filename)

        # Download the XPI to make sure the url is actually good
        res = api_client.get(res.data["xpi"], follow=True)
        assert res.status_code == 200
开发者ID:rehandalal,项目名称:normandy,代码行数:10,代码来源:test_api.py


示例19: show_single_search

def show_single_search(show, embed=None):
    show = url_quote(show)
    if embed:
        url = endpoints.show_single_search.format(show) + '&embed=' + embed
    else:
        url = endpoints.show_single_search.format(show)
    q = query_endpoint(url)
    if q:
        return q
    else:
        raise ShowNotFound(str(show) + ' not found')
开发者ID:Murodese,项目名称:pytvmaze,代码行数:11,代码来源:tvmaze.py


示例20: get_formatted_verification_link

def get_formatted_verification_link(verification_code, partial_link):
    ''' Create a link for the verification code. '''

    try:
        code = verification_code
        quoted_code = url_quote(code)
        link = '/mail/{}/{}'.format(partial_link, quoted_code, code)
    except:
        link = code

    return link
开发者ID:goodcrypto,项目名称:goodcrypto-mail,代码行数:11,代码来源:message_security.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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