当前位置: 首页>>代码示例>>Python>>正文


Python parse.unquote_plus方法代码示例

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


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

示例1: POST

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def POST(self):
        """
        Get client key status.
        /client/status
        """
        # LDAP authentication
        is_auth, message = tools.ldap_authentification(SERVER_OPTS)
        if not is_auth:
            return tools.response_render(message, http_code='401 Unauthorized')

        payload, message = tools.data2map()
        if message:
            return tools.response_render(message, http_code='400 Bad Request')

        if 'realname' in payload:
            realname = unquote_plus(payload['realname'])
        else:
            return tools.response_render(
                'Error: No realname option given.',
                http_code='400 Bad Request')

        return tools.response_render(
            TOOLS.list_keys(realname=realname),
            content_type='application/json') 
开发者ID:nbeguier,项目名称:cassh,代码行数:26,代码来源:server.py

示例2: parse_userinfo

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def parse_userinfo(userinfo):
    """Validates the format of user information in a MongoDB URI.
    Reserved characters like ':', '/', '+' and '@' must be escaped
    following RFC 2396.

    Returns a 2-tuple containing the unescaped username followed
    by the unescaped password.

    :Paramaters:
        - `userinfo`: A string of the form <username>:<password>

    .. versionchanged:: 2.2
       Now uses `urllib.unquote_plus` so `+` characters must be escaped.
    """
    if '@' in userinfo or userinfo.count(':') > 1:
        raise InvalidURI("':' or '@' characters in a username or password "
                         "must be escaped according to RFC 2396.")
    user, _, passwd = _partition(userinfo, ":")
    # No password is expected with GSSAPI authentication.
    if not user:
        raise InvalidURI("The empty string is not valid username.")
    user = unquote_plus(user)
    passwd = unquote_plus(passwd)

    return user, passwd 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:uri_parser.py

示例3: _parse_options

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def _parse_options(opts, delim):
    """Helper method for split_options which creates the options dict.
    Also handles the creation of a list for the URI tag_sets/
    readpreferencetags portion."""
    options = {}
    for opt in opts.split(delim):
        key, val = opt.split("=")
        if key.lower() == 'readpreferencetags':
            options.setdefault('readpreferencetags', []).append(val)
        else:
            # str(option) to ensure that a unicode URI results in plain 'str'
            # option names. 'normalized' is then suitable to be passed as
            # kwargs in all Python versions.
            if str(key) in options:
                warnings.warn("Duplicate URI option %s" % (str(key),))
            options[str(key)] = unquote_plus(val)

    # Special case for deprecated options
    if "wtimeout" in options:
        if "wtimeoutMS" in options:
            options.pop("wtimeout")
        warnings.warn("Option wtimeout is deprecated, use 'wtimeoutMS'"
                      " instead")

    return options 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:27,代码来源:uri_parser.py

示例4: format_url_show

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def format_url_show(url:str, urlenc='utf-8'):
    # return str
    indent = 4
    url = ps.unquote_plus(url, encoding=urlenc)
    pls = re.findall('\?[^&]*|&[^&]*',url)
    pms = [None]
    for i in pls:
        url = url.replace(i,'',1) # fix
        if len(i) > 50 and ',' in i:
            _pms = []
            for j in i.split(','):
                j = ' '*indent + j + ','
                _pms.append(j)
            _pms[-1] = _pms[-1][:-1]
            pms += _pms
        else:
            pms.append(i)
    pms[0] = url
    return '\n'.join(pms) 
开发者ID:cilame,项目名称:vrequest,代码行数:21,代码来源:util.py

示例5: _delete_objects

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def _delete_objects(bucket: str, keys: List[str], client_s3: boto3.client, attempt: int = 1) -> None:
    _logger.debug("len(keys): %s", len(keys))
    batch: List[Dict[str, str]] = [{"Key": key} for key in keys]
    res = client_s3.delete_objects(Bucket=bucket, Delete={"Objects": batch})
    deleted: List[Dict[str, Any]] = res.get("Deleted", [])
    for obj in deleted:
        _logger.debug("s3://%s/%s has been deleted.", bucket, obj.get("Key"))
    errors: List[Dict[str, Any]] = res.get("Errors", [])
    internal_errors: List[str] = []
    for error in errors:
        if error["Code"] != "InternalError":
            raise exceptions.ServiceApiError(errors)
        internal_errors.append(_unquote_plus(error["Key"]))
    if len(internal_errors) > 0:
        if attempt > 5:  # Maximum of 5 attempts (Total of 15 seconds)
            raise exceptions.ServiceApiError(errors)
        time.sleep(attempt)  # Incremental delay (linear)
        _delete_objects(bucket=bucket, keys=internal_errors, client_s3=client_s3, attempt=(attempt + 1)) 
开发者ID:awslabs,项目名称:aws-data-wrangler,代码行数:20,代码来源:_delete.py

示例6: url_unescape

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def url_unescape(value, encoding='utf-8', plus=True):
        """Decodes the given value from a URL.

        The argument may be either a byte or unicode string.

        If encoding is None, the result will be a byte string.  Otherwise,
        the result is a unicode string in the specified encoding.

        If ``plus`` is true (the default), plus signs will be interpreted
        as spaces (literal plus signs must be represented as "%2B").  This
        is appropriate for query strings and form-encoded values but not
        for the path component of a URL.  Note that this default is the
        reverse of Python's urllib module.

        .. versionadded:: 3.1
           The ``plus`` argument
        """
        unquote = (urllib_parse.unquote_plus if plus else urllib_parse.unquote)
        if encoding is None:
            return unquote(utf8(value))
        else:
            return unicode_type(unquote(utf8(value)), encoding) 
开发者ID:tp4a,项目名称:teleport,代码行数:24,代码来源:escape.py

示例7: authorization_required

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def authorization_required(func):
    @wraps(func)
    @coroutine
    def wrap(self, *args, **kwargs):
        auth_header = self.request.headers.get('Authorization')
        if not auth_header:
            self.set_header('WWW-Authenticate', 'Basic realm="pypi"')
            self.set_status(401)
            raise Return(self.finish("Authorization required"))

        auth_type, data = auth_header.split()
        if auth_type.lower() != 'basic':
            raise Return(self.send_error(400))

        username, password = map(lambda x: unquote_plus(x.decode("utf-8")), base64.b64decode(b(data)).split(b(":")))
        try:
            self.current_user = yield check_password(username, password)
        except LookupError:
            raise HTTPError(403)

        result = yield maybe_future(func(self, *args, **kwargs))
        raise Return(result)

    return wrap 
开发者ID:mosquito,项目名称:pypi-server,代码行数:26,代码来源:package.py

示例8: load

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def load(self, issuer):
        if not self._data_uri.startswith('data:application/pkcs8;kid='):
            raise PrivateKeyRetrieverException('Unrecognised data uri format.')
        splitted = self._data_uri.split(';')
        key_identifier = KeyIdentifier(unquote_plus(
            splitted[1][len('kid='):]))
        key_data = base64.b64decode(splitted[-1].split(',')[-1])
        key = serialization.load_der_private_key(
            key_data,
            password=None,
            backend=cryptography.hazmat.backends.default_backend())
        private_key_pem = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        )
        return key_identifier, private_key_pem.decode('utf-8') 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:19,代码来源:key.py

示例9: _get_co_name_from_path

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def _get_co_name_from_path(self, context):
        """
        The CO name is URL encoded and obtained from the request path
        for a request coming into one of the standard binding endpoints.
        For example the HTTP-Redirect binding request path will have the
        format

        {base}/{backend}/{co_name}/sso/redirect

        :type context: satosa.context.Context
        :rtype: str

        :param context:

        """
        url_encoded_co_name = context.path.split("/")[1]
        co_name = unquote_plus(url_encoded_co_name)

        return co_name 
开发者ID:IdentityPython,项目名称:SATOSA,代码行数:21,代码来源:saml2.py

示例10: process_key_event

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def process_key_event(event, context):
    processor = EncryptExtantKeys(config)
    for record in event.get('Records', []):
        bucket = record['s3']['bucket']['name']
        key = {'Key': unquote_plus(record['s3']['object']['key']),
               'Size': record['s3']['object']['size']}
        version = record['s3']['object'].get('versionId')
        if version is not None:
            key['VersionId'] = version
            # lambda event is always latest version, but IsLatest
            # is not in record
            key['IsLatest'] = True
            method = processor.process_version
        else:
            method = processor.process_key
        try:
            result = retry(method, s3, key, bucket)
        except ClientError as e:
            # Ensure we know which key caused an issue
            print("error %s:%s code:%s" % (
                bucket, key['Key'], e.response['Error']))
            raise
        if not result:
            return
        print("remediated %s:%s" % (bucket, key['Key'])) 
开发者ID:cloud-custodian,项目名称:cloud-custodian,代码行数:27,代码来源:s3crypt.py

示例11: remove_operator

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def remove_operator(request, name, user):
    if user['auth'] not in ['access_token', 'apitoken']:
        abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
    name = unquote_plus(name)
    if name != user['username'] and not user['admin']:
        return json({'status': 'error', 'error': 'cannot delete anybody but yourself unless you\'re admin'})
    try:
        query = await db_model.operator_query()
        op = await db_objects.get(query, username=name)
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to find operator'})
    try:
        op.deleted = True
        await db_objects.update(op)
        success = {'status': 'success'}
        return json({**success, **op.to_json()})
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to mark operator as deleted'}) 
开发者ID:its-a-feature,项目名称:Apfell,代码行数:22,代码来源:operator_api.py

示例12: get_transforms_by_type

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def get_transforms_by_type(request, ptype, user):
    if user['auth'] not in ['access_token', 'apitoken']:
        abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
    payload_type = unquote_plus(ptype)
    try:
        query = await db_model.payloadtype_query()
        payloadtype = await db_objects.get(query, ptype=payload_type)
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to find payload type'})
    try:
        query = await db_model.transform_query()
        transforms = await db_objects.execute(query.where(Transform.payload_type == payloadtype).order_by(
            Transform.t_type, Transform.order
        ))
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to get the transforms'})
    return json({'status': 'success', 'transforms': [t.to_json() for t in transforms]}) 
开发者ID:its-a-feature,项目名称:Apfell,代码行数:21,代码来源:transform_api.py

示例13: get_file_list_for_c2profiles

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def get_file_list_for_c2profiles(request, info, user):
    if user['auth'] not in ['access_token', 'apitoken']:
        abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
    name = unquote_plus(info)
    try:
        query = await db_model.c2profile_query()
        profile = await db_objects.get(query, name=name)
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to find C2 Profile'})
    try:
        path = "./app/c2_profiles/{}/".format(profile.name)
        files = []
        for (dirpath, dirnames, filenames) in os.walk(path):
            if dirpath != path:
                files.append({"folder": dirpath.replace(path, ""), "dirnames": dirnames, "filenames": filenames})
        return json({'status': 'success', 'files': files})
    except Exception as e:
        return json({'status': 'error', 'error': 'failed getting files: ' + str(e)})


# Get c2 profile files listing for the user 
开发者ID:its-a-feature,项目名称:Apfell,代码行数:24,代码来源:c2profiles_api.py

示例14: get_filename_from_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def get_filename_from_url(url):
    return unquote_plus(urlparse(url).path.split("/")[-1]) 
开发者ID:mozilla,项目名称:normandy,代码行数:4,代码来源:0014_auto_20190228_1128.py

示例15: parse_custom_verification_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def parse_custom_verification_url(url, verification_field_names):
    parsed_url = urlparse(url)
    num_of_fields = len(verification_field_names)
    url_path = parsed_url.path.rstrip('/')
    url_segments = url_path.rsplit('/', num_of_fields)
    if len(url_segments) != num_of_fields + 1:
        raise ValueError("Could not parse {url}".format(url=url))

    data_segments = url_segments[1:]
    url_path = url_segments[0] + '/'
    verification_data = {
        name: urlunquote(value)
        for name, value in zip(verification_field_names, data_segments)}
    return url_path, verification_data 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:16,代码来源:test_register.py


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