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


Python base64.urlsafe_b64encode方法代码示例

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


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

示例1: __call__

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def __call__(self, method, request):
        """
        Args:
            method (str): Client Authentication Method. Only 'client_secret_basic' and 'client_secret_post' is
                supported.
            request (MutableMapping[str, str]): Token request parameters. This may be modified, i.e. if
                'client_secret_post' is used the client credentials will be added.

        Returns:
            (Mapping[str, str]): HTTP headers to be included in the token request, or `None` if no extra HTTPS headers
            are required for the token request.
        """
        if method == 'client_secret_post':
            request['client_id'] = self._client_id
            request['client_secret'] = self._client_secret
            return None  # authentication is in the request body, so no Authorization header is returned

        # default to 'client_secret_basic'
        credentials = '{}:{}'.format(self._client_id, self._client_secret)
        basic_auth = 'Basic {}'.format(base64.urlsafe_b64encode(credentials.encode('utf-8')).decode('utf-8'))
        return {'Authorization': basic_auth} 
开发者ID:zamzterz,项目名称:Flask-pyoidc,代码行数:23,代码来源:pyoidc_facade.py

示例2: _get_key

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
开发者ID:rtshome,项目名称:pgrepup,代码行数:22,代码来源:crypt.py

示例3: choose_image

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def choose_image(self):
        image_file = filedialog.askopenfilename(filetypes=self.image_file_types)

        if image_file:
            avatar = Image.open(image_file)
            avatar.thumbnail((128, 128))
            avatar.save(avatar_file_path, "PNG")

            img_contents = ""
            img_b64 = ""
            with open(avatar_file_path, "rb") as img:
                img_contents = img.read()
                img_b64 = base64.urlsafe_b64encode(img_contents)

            self.master.requester.update_avatar(self.master.username, img_b64)

            self.current_avatar_image = tk.PhotoImage(file=avatar_file_path)
            self.current_avatar.configure(image=self.current_avatar_image) 
开发者ID:PacktPublishing,项目名称:Tkinter-GUI-Programming-by-Example,代码行数:20,代码来源:avatarwindow.py

示例4: qute_settings

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def qute_settings(url: QUrl) -> _HandlerRet:
    """Handler for qute://settings. View/change qute configuration."""
    global csrf_token

    if url.path() == '/set':
        if url.password() != csrf_token:
            message.error("Invalid CSRF token for qute://settings!")
            raise RequestDeniedError("Invalid CSRF token!")
        return _qute_settings_set(url)

    # Requests to qute://settings/set should only be allowed from
    # qute://settings. As an additional security precaution, we generate a CSRF
    # token to use here.
    if secrets:
        csrf_token = secrets.token_urlsafe()
    else:
        # On Python < 3.6, from secrets.py
        token = base64.urlsafe_b64encode(os.urandom(32))
        csrf_token = token.rstrip(b'=').decode('ascii')

    src = jinja.render('settings.html', title='settings',
                       configdata=configdata,
                       confget=config.instance.get_str,
                       csrf_token=csrf_token)
    return 'text/html', src 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:27,代码来源:qutescheme.py

示例5: sri_hash

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def sri_hash(data, url_safe=False):
    """
    Return a subresource integrity attribute string for a file
    containing the given binary data.

    SRI attributes are a string of the form "{algorithm}-{hash}", where
    {algorithm} is the hash algorithm, and {hash} is a base64-encoded
    hash of the data using the specified algorithm.

    :param data:
        Bytes-like object containing the data to hash.
    """
    digest = sha384(data).digest()
    if url_safe:
        data_hash = urlsafe_b64encode(digest)
    else:
        data_hash = b64encode(digest)
    return "sha384-" + data_hash.decode() 
开发者ID:mozilla,项目名称:normandy,代码行数:20,代码来源:utils.py

示例6: _write_file

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def _write_file(self, archive, path: str, fpath: Path) -> None:
        # write content into archive
        archive.write(filename=str(fpath), arcname=path, compress_type=ZIP_DEFLATED)

        # calculate hashsum
        # https://stackoverflow.com/questions/22058048/hashing-a-file-in-python
        digest = sha256()
        with fpath.open('rb') as stream:
            while True:
                data = stream.read(65536)
                if not data:
                    break
                digest.update(data)
        digest = urlsafe_b64encode(digest.digest()).decode().rstrip('=')

        self._records.append((path, digest, fpath.stat().st_size)) 
开发者ID:dephell,项目名称:dephell,代码行数:18,代码来源:wheel.py

示例7: test_base64

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def test_base64(self):
    """Test automatic decoding of a base-64-encoded message."""
    # Create upload.
    upload_data = (
        """--================1234==
Content-Type: text/plain
MIME-Version: 1.0
Content-Disposition: form-data; name="field1"; filename="stuff.txt"
Content-Transfer-Encoding: base64

%s
--================1234==--""" % base64.urlsafe_b64encode('value'))

    upload_url = blobstore.create_upload_url('/success')

    upload, forward_environ, _ = self._run_test_success(
        upload_data, upload_url)

    self.assertEquals('/success', forward_environ['PATH_INFO'])
    self.assertEquals(
        ('form-data', {'filename': 'stuff.txt', 'name': 'field1'}),
        cgi.parse_header(upload['content-disposition'])) 
开发者ID:elsigh,项目名称:browserscope,代码行数:24,代码来源:blob_upload_test.py

示例8: create_blob

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def create_blob(self):
    """Create a GS object in the datastore and on disk.

    Overrides the superclass create_blob method.

    Returns:
      The BlobKey of the new object."
    """
    data = 'a blob'
    filename = '/gs/some_bucket/some_object'
    blob_store_key = base64.urlsafe_b64encode(filename)
    self.blob_storage.StoreBlob(blob_store_key, cStringIO.StringIO(data))

    blob_key = blobstore.create_gs_key(filename)
    entity = datastore.Entity(file_service_stub.GS_INFO_KIND,
                              name=blob_key,
                              namespace='')
    entity['content_type'] = 'image/png'
    entity['filename'] = 'largeblob.png'
    entity['size'] = len(data)
    entity['storage_key'] = blob_store_key
    datastore.Put(entity)

    return blob_key 
开发者ID:elsigh,项目名称:browserscope,代码行数:26,代码来源:blob_download_test.py

示例9: post

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def post(self, endpoint, data, params=None, raw=False, headers=None):
        HMAC = self.HMAC.copy()
        path = self.base_path + endpoint
        method = 'POST'
        hdrs = {}
        window = int(time.time()) // 5
        if not raw:
            hdrs = {'Content-Type': 'application/json'}
            body = json.dumps(data)
        else:
            hdrs = headers if headers else {}
            body = data

        if params:
            path = ''.join([path, '?', urlencode(params)])
        text = '%s %s %s %s' % (window, method, path, body)
        text = text.encode('utf8')
        HMAC.update(text)
        digest = base64.urlsafe_b64encode(HMAC.digest())

        auth_header = 'hmac %s:' % self.user
        hdrs['Authorization'] = auth_header.encode('utf8') + digest

        return self.urlopen(method, path, headers=hdrs, body=body) 
开发者ID:linkedin,项目名称:iris-relay,代码行数:26,代码来源:client.py

示例10: get

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def get(self, endpoint, params=None, raw=False):
        HMAC = self.HMAC.copy()
        path = self.base_path + endpoint
        method = 'GET'
        window = int(time.time()) // 5
        body = ''
        if params:
            path = ''.join([path, '?', urlencode(params)])
        text = '%s %s %s %s' % (window, method, path, body)
        text = text.encode('utf8')
        HMAC.update(text)
        digest = base64.urlsafe_b64encode(HMAC.digest())

        auth_header = 'hmac %s:' % self.user
        headers = {
            'Content-Type': 'application/json',
            'Authorization': auth_header.encode('utf8') + digest
        }
        return self.urlopen(method, path, headers=headers) 
开发者ID:linkedin,项目名称:iris-relay,代码行数:21,代码来源:client.py

示例11: b64url_encode

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def b64url_encode(b):
    return base64.urlsafe_b64encode(b).decode() 
开发者ID:pyauth,项目名称:pywarp,代码行数:4,代码来源:__init__.py

示例12: basic_auth

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def basic_auth(self):
        credentials = '{}:{}'.format(self.CLIENT_ID, self.CLIENT_SECRET)
        return 'Basic {}'.format(base64.urlsafe_b64encode(credentials.encode('utf-8')).decode('utf-8')) 
开发者ID:zamzterz,项目名称:Flask-pyoidc,代码行数:5,代码来源:test_pyoidc_facade.py

示例13: embed_real_url_to_embedded_url

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def embed_real_url_to_embedded_url(real_url_raw, url_mime, escape_slash=False):
    """
    将url的参数(?q=some&foo=bar)编码到url路径中, 并在url末添加一个文件扩展名
    在某些对url参数支持不好的CDN中, 可以减少错误
    `cdn_redirect_encode_query_str_into_url`设置依赖于本函数, 详细说明可以看配置文件中的对应部分
    解码由 extract_real_url_from_embedded_url() 函数进行, 对应的例子也请看这个函数
    :rtype: str
    """
    # dbgprint(real_url_raw, url_mime, escape_slash)
    if escape_slash:
        real_url = real_url_raw.replace(r'\/', '/')
    else:
        real_url = real_url_raw
    url_sp = urlsplit(real_url)
    if not url_sp.query:  # no query, needn't rewrite
        return real_url_raw

    byte_query = url_sp.query.encode()
    if len(byte_query) > 128:  # 当查询参数太长时, 进行gzip压缩
        gzip_label = 'z'  # 进行压缩后的参数, 会在标识区中添加一个z
        byte_query = zlib.compress(byte_query)
    else:
        gzip_label = ''

    b64_query = base64.urlsafe_b64encode(byte_query).decode()
    # dbgprint(url_mime)
    mixed_path = url_sp.path + '_' + _url_salt + gzip_label + '_.' \
                 + b64_query \
                 + '._' + _url_salt + '_.' + mime_to_use_cdn[url_mime]
    result = urlunsplit((url_sp.scheme, url_sp.netloc, mixed_path, '', ''))

    if escape_slash:
        result = s_esc(result)
        # dbgprint('embed:', real_url_raw, 'to:', result)
    return result 
开发者ID:aploium,项目名称:zmirror,代码行数:37,代码来源:utils.py

示例14: filter_client_request

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def filter_client_request():
    """过滤用户请求, 视情况拒绝用户的访问
    :rtype: Union[Response, None]
    """
    dbgprint('Client Request Url: ', request.url)

    # crossdomain.xml
    if os.path.basename(request.path) == 'crossdomain.xml':
        dbgprint('crossdomain.xml hit from', request.url)
        return crossdomain_xml()

    # Global whitelist ua
    if check_global_ua_pass(str(request.user_agent)):
        return None

    if is_deny_spiders_by_403 and is_denied_because_of_spider(str(request.user_agent)):
        return generate_simple_resp_page(b'Spiders Are Not Allowed To This Site', 403)

    if human_ip_verification_enabled and (
                ((human_ip_verification_whitelist_from_cookies or enable_custom_access_cookie_generate_and_verify)
                 and must_verify_cookies)
            or is_ip_not_in_allow_range(request.remote_addr)
    ):
        dbgprint('ip', request.remote_addr, 'is verifying cookies')
        if 'zmirror_verify' in request.cookies and \
                ((human_ip_verification_whitelist_from_cookies and verify_ip_hash_cookie(request.cookies.get('zmirror_verify')))
                 or (enable_custom_access_cookie_generate_and_verify and custom_verify_access_cookie(
                        request.cookies.get('zmirror_verify'), request))):
            ip_whitelist_add(request.remote_addr, info_record_dict=request.cookies.get('zmirror_verify'))
            dbgprint('add to ip_whitelist because cookies:', request.remote_addr)
        else:
            return redirect(
                "/ip_ban_verify_page?origin=" + base64.urlsafe_b64encode(str(request.url).encode(encoding='utf-8')).decode(
                    encoding='utf-8'),
                code=302)

    return None 
开发者ID:aploium,项目名称:zmirror,代码行数:39,代码来源:zmirror.py

示例15: __key_url

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import urlsafe_b64encode [as 别名]
def __key_url(self, key):
        urlSafeEncodedBytes = base64.urlsafe_b64encode(key.encode("utf-8"))
        urlSafeEncodedStr = str(urlSafeEncodedBytes, "utf-8")
        url = self.endpoint + '/rest/v2/caches/' + self.cache_name + '/' + urlSafeEncodedStr
        return url 
开发者ID:pywren,项目名称:pywren-ibm-cloud,代码行数:7,代码来源:infinispan.py


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