當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。