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方法的24个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: validate_payload

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def validate_payload(key, value):
    """
    Return an error message if invalid input
    """
    new_value = unquote_plus(value)
    count = 10
    while value != new_value and count > 0 and \
        key in ['username', 'principals', 'add', 'remove', 'update', 'filter', 'realname']:
        value = new_value
        new_value = unquote_plus(value)
        count -= 1
    err_msg = None
    if key == 'username' and constants.PATTERN_USERNAME.match(value) is None:
        err_msg = "Error: invalid username."
    elif key == 'realname' and constants.PATTERN_REALNAME.match(value) is None:
        err_msg = "Error: invalid realname."
    elif key == 'expiry' and constants.PATTERN_EXPIRY.match(value) is None:
        err_msg = "Error: invalid expiry."
    elif key in ['principals', 'add', 'remove', 'update']:
        for principal in value.split(','):
            if constants.PATTERN_PRINCIPALS.match(principal) is None:
                err_msg = "Error: invalid principals."
    elif key == 'filter':
        if value != '':
            for principal in value.split(','):
                if constants.PATTERN_PRINCIPALS.match(principal) is None:
                    err_msg = "Error: invalid filter."
    return err_msg 
开发者ID:nbeguier,项目名称:cassh,代码行数:32,代码来源:tools.py


示例17: unquote_custom

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def unquote_custom(string):
    """
    Returns True is the string is quoted
    """
    if ' ' not in string:
        string = unquote_plus(string)
        if '+' in string and '%20' in string:
            # Old custom quote
            string = string.replace('%20', ' ')
    return string 
开发者ID:nbeguier,项目名称:cassh,代码行数:12,代码来源:tools.py


示例18: compute_signature

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def compute_signature(token, uri, post_body, utf=False):
    """Compute the signature for a given request
    :param uri: full URI that Twilio requested on your server
    :param post_body: post vars that Twilio sent with the request, list of str
    :param utf: whether return should be bytestring or unicode (python3)
    :returns: The computed signature
    """
    s = uri
    if len(post_body) > 0:
        p_b_split = post_body.decode().split('&')
        lst = [unquote_plus(kv.replace('=', ''))
               for kv in sorted(p_b_split)]
        lst.insert(0, s)
        s = ''.join(lst)
    s = s.encode('utf8')
    token = token.encode('utf8')
    # compute signature and compare signatures
    if isinstance(s, bytes):
        mac = hmac.new(token, s, sha1)
    else:
        # Should never happen
        raise TypeError
    computed = b64encode(mac.digest())
    if utf:
        computed = computed.decode('utf-8')
    return computed.strip() 
开发者ID:linkedin,项目名称:iris-relay,代码行数:31,代码来源:app.py


示例19: get_signature

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def get_signature(key: str, data: dict):
    """
    签名过程如下:
    0. 忽略已经存在的 sign
    1. 将所有参数名按照字典序排列,并以 "参数1=值1&参数2=值2&参数3=值3" 的形式排序
    2. 将上面的内容加上 "&key=KEY"(KEY 为设置的商户密钥)
    3. 将组合后的字符串转换为大写 MD5
    :param key: 商户密钥
    :param data: 要签名的参数字典
    :return: 签名后的字符串
    :rtype: str
    """
    d = data.copy()
    # pop 掉 sign 字段
    try:
        d.pop('sign')
    except KeyError:
        pass
    # pop 掉无效字段
    p = sorted([x for x in d.items() if (x[1] or x[1] == 0)], key=lambda x: x[0])
    p.append(('key', key))
    p = unquote_plus(urlencode(p))
    h = md5()
    h.update(p.encode())
    r = h.hexdigest().upper()
    return r 
开发者ID:ImSingee,项目名称:PayJS,代码行数:36,代码来源:sign.py


示例20: unpack

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def unpack(code):
    """URL decode `code` source string."""
    return unquote_plus(code) if detect(code) else code 
开发者ID:omriher,项目名称:CapTipper,代码行数:5,代码来源:urlencode.py


示例21: unquote_str

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def unquote_str(value, encoding='utf-8'):
        # In python2, unquote() gives us a string back that has the urldecoded
        # bits, but not the unicode parts.  We need to decode this manually.
        # unquote has special logic in which if it receives a unicode object it
        # will decode it to latin1.  This is hard coded.  To avoid this, we'll
        # encode the string with the passed in encoding before trying to
        # unquote it.
        byte_string = value.encode(encoding)
        return unquote_plus(byte_string).decode(encoding) 
开发者ID:skarlekar,项目名称:faces,代码行数:11,代码来源:compat.py


示例22: 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 3986.
    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:
        if PY3:
            quote_fn = "urllib.parse.quote_plus"
        else:
            quote_fn = "urllib.quote_plus"
        raise InvalidURI("Username and password must be escaped according to "
                         "RFC 3986, use %s()." % quote_fn)
    user, _, passwd = _partition(userinfo, ":")
    # No password is expected with GSSAPI authentication.
    if not user:
        raise InvalidURI("The empty string is not valid username.")
    return unquote_plus(user), unquote_plus(passwd) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:28,代码来源:uri_parser.py


示例23: _discover_inputimage

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def _discover_inputimage(self, input_string):
        patt = re.match(".*(sha256:.*)", input_string)
        if patt:
            urldigest = quote_plus(patt.group(1))
            return "digest", input_string, urldigest
        try:
            digest = unquote_plus(str(input_string))
            for tpe in ["sha256", "local"]:
                patt = re.match(".*({}:.*)".format(tpe), digest)
                if patt:
                    return "imageDigest", input_string, input_string
        except Exception:
            pass
        urldigest = None
        ret_type = "tag"
        ok, ret = self.get_image(input_string)
        if ok:
            image_record = ret[0]
            urldigest = image_record.get('imageDigest', None)
            for image_detail in image_record.get('image_detail', []):
                if input_string == image_detail.get('imageId', ''):
                    ret_type = "imageid"
                    break
        return ret_type, input_string, urldigest 
开发者ID:draios,项目名称:python-sdc-client,代码行数:29,代码来源:_scanning.py


示例24: remove_signed_prefix_as_needed

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import unquote_plus [as 别名]
def remove_signed_prefix_as_needed(url):
    if url is None:
        return
    if url.startswith(SIGNED_URL_PREFIX):
        return unquote_plus(url[len(S3_URL_PREFIX) :])
    elif url.startswith(S3_URL_PREFIX_ENCODED):
        parsed = urlparse(url.replace(S3_URL_PREFIX_ENCODED, S3_URL_PREFIX))
        return "{}://{}{}".format(parsed.scheme, parsed.netloc, parsed.path)
    else:
        return url 
开发者ID:jamalex,项目名称:notion-py,代码行数:12,代码来源:utils.py



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