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