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


Python base64.b64encode方法代码示例

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


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

示例1: get_qrcode_url

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def get_qrcode_url(self, ticket, data=None):
        """
        通过 ticket 换取二维码地址
        详情请参考
        https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4

        :param ticket: 二维码 ticket
        :param data: 额外数据
        :return: 二维码地址
        """
        url = f"https://we.qq.com/d/{ticket}"
        if data:
            if isinstance(data, (dict, tuple, list)):
                data = urllib.urlencode(data)
            data = to_text(base64.b64encode(to_binary(data)))
            url = f"{url}#{data}"
        return url 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:19,代码来源:device.py

示例2: get_kms_auth_token

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def get_kms_auth_token(session, bless_config, lambda_regional_config):
    logger.info("Requesting new KMS auth token in %s", lambda_regional_config["aws_region"])
    token_not_before = datetime.datetime.utcnow() - datetime.timedelta(minutes=1)
    token_not_after = token_not_before + datetime.timedelta(hours=1)
    token = dict(not_before=token_not_before.strftime("%Y%m%dT%H%M%SZ"),
                 not_after=token_not_after.strftime("%Y%m%dT%H%M%SZ"))
    encryption_context = {
        "from": session.resource("iam").CurrentUser().user_name,
        "to": bless_config["lambda_config"]["function_name"],
        "user_type": "user"
    }
    kms = session.client('kms', region_name=lambda_regional_config["aws_region"])
    res = kms.encrypt(KeyId=lambda_regional_config["kms_auth_key_id"],
                      Plaintext=json.dumps(token),
                      EncryptionContext=encryption_context)
    return base64.b64encode(res["CiphertextBlob"]).decode() 
开发者ID:kislyuk,项目名称:aegea,代码行数:18,代码来源:ssh.py

示例3: get_dockerfile

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def get_dockerfile(args):
    if args.dockerfile:
        return io.open(args.dockerfile, "rb").read()
    else:
        cmd = bash_cmd_preamble + [
            "apt-get update -qq",
            "apt-get install -qqy cloud-init net-tools",
            "echo $CLOUD_CONFIG_B64 | base64 --decode > /etc/cloud/cloud.cfg.d/99_aegea.cfg",
            "cloud-init init",
            "cloud-init modules --mode=config",
            "cloud-init modules --mode=final"
        ]
        return dockerfile.format(base_image=args.base_image,
                                 maintainer=ARN.get_iam_username(),
                                 label=" ".join(args.tags),
                                 cloud_config_b64=base64.b64encode(get_cloud_config(args)).decode(),
                                 run=json.dumps(cmd)).encode() 
开发者ID:kislyuk,项目名称:aegea,代码行数:19,代码来源:build_docker_image.py

示例4: create

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def create(args):
    vpc = ensure_vpc()
    if args.security_groups is None:
        args.security_groups = [__name__]
        ensure_security_group(__name__, vpc, tcp_ingress=[dict(port=socket.getservbyname("nfs"),
                                                               source_security_group_name=__name__)])
    creation_token = base64.b64encode(bytearray(os.urandom(24))).decode()
    args.tags.append("Name=" + args.name)
    create_file_system_args = dict(CreationToken=creation_token,
                                   PerformanceMode=args.performance_mode,
                                   ThroughputMode=args.throughput_mode,
                                   Tags=encode_tags(args.tags))
    if args.throughput_mode == "provisioned":
        create_file_system_args.update(ProvisionedThroughputInMibps=args.provisioned_throughput_in_mibps)
    fs = clients.efs.create_file_system(**create_file_system_args)
    waiter = make_waiter(clients.efs.describe_file_systems, "FileSystems[].LifeCycleState", "available", "pathAny")
    waiter.wait(FileSystemId=fs["FileSystemId"])
    security_groups = [resolve_security_group(g, vpc).id for g in args.security_groups]
    for subnet in vpc.subnets.all():
        clients.efs.create_mount_target(FileSystemId=fs["FileSystemId"],
                                        SubnetId=subnet.id,
                                        SecurityGroups=security_groups)
    return fs 
开发者ID:kislyuk,项目名称:aegea,代码行数:25,代码来源:efs.py

示例5: rsa_encrypt

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def rsa_encrypt(data, pem, b64_encode=True):
    """
    rsa 加密
    :param data: 待加密字符串/binary
    :param pem: RSA public key 内容/binary
    :param b64_encode: 是否对输出进行 base64 encode
    :return: 如果 b64_encode=True 的话,返回加密并 base64 处理后的 string;否则返回加密后的 binary
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encoded_data = to_binary(data)
    pem = to_binary(pem)
    public_key = serialization.load_pem_public_key(pem, backend=default_backend())
    encrypted_data = public_key.encrypt(
        encoded_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
    )
    if b64_encode:
        encrypted_data = base64.b64encode(encrypted_data).decode("utf-8")
    return encrypted_data 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:24,代码来源:utils.py

示例6: send_message

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def send_message(self, device_type, device_id, user_id, content):
        """
        主动发送消息给设备
        详情请参考
        https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-3

        :param device_type: 设备类型,目前为“公众账号原始ID”
        :param device_id: 设备ID
        :param user_id: 微信用户账号的openid
        :param content: 消息内容,BASE64编码
        :return: 返回的 JSON 数据包
        """
        content = to_text(base64.b64encode(to_binary(content)))
        return self._post(
            "transmsg",
            data={"device_type": device_type, "device_id": device_id, "open_id": user_id, "content": content,},
        ) 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:19,代码来源:device.py

示例7: serialize_ndarray_b64

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def serialize_ndarray_b64(o):
    """
    Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are
    human-readable, but the array data itself is binary64 encoded.

    Args:
        o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    if o.flags['C_CONTIGUOUS']:
        o_data = o.data
    else:
        o_data = np.ascontiguousarray(o).data
    data_b64 = base64.b64encode(o_data)
    return dict(
        _type='np.ndarray',
        data=data_b64.decode('utf-8'),
        dtype=o.dtype,
        shape=o.shape) 
开发者ID:gregreen,项目名称:dustmaps,代码行数:23,代码来源:json_serializers.py

示例8: lan_event

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def lan_event(self):
        '''变更语言的方法'''
        #读取本地配置文件
        num = 0
        with open(".\data.ini",'rb') as f:
            self.lan_data = f.readlines()
        with open(".\data.ini",'wb') as f:
            for line in self.lan_data:
                if num == self.dual_host_view.currentRow() + 1:
                    data = base64.b64decode(line)
                    data = json.loads(data.decode())
                    data['lan'] = self.lan_input.currentIndex()
                    f.write(base64.b64encode(json.dumps(data).encode()))
                    f.write('\n'.encode())
                else:
                    f.write(line)
                num += 1

        a = QMessageBox()
        #写入成功提示
        a.information(a,self.tr("Success"),self.tr("Language will be changed after resrart the application")) 
开发者ID:Pryriat,项目名称:BandwagongVPS_controller,代码行数:23,代码来源:bwh_ctr.py

示例9: dual_host_select_event

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def dual_host_select_event(self):
        num = 0
        with open(".\data.ini",'rb') as f:
            self.tmp_data = f.readlines()
        with open(".\data.ini",'wb') as f:
            for x in self.tmp_data:
                if not len(x.strip()):
                    pass
                if num == 0:
                    f.write(base64.b64encode(str(self.dual_host_view.currentRow()+1).encode()))
                    f.write('\n'.encode())
                else:
                    f.write(x)
                num += 1

        a = QMessageBox()
        #写入成功提示
        a.information(a,self.tr("Success"),self.tr("host will be changed after resrart the application")) 
开发者ID:Pryriat,项目名称:BandwagongVPS_controller,代码行数:20,代码来源:bwh_ctr.py

示例10: test_get_private_registry_config

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def test_get_private_registry_config(self, mock_requests):
        registry = {'username': 'test', 'password': 'test'}
        auth = bytes('{}:{}'.format("test", "test"), 'UTF-8')
        encAuth = base64.b64encode(auth).decode(encoding='UTF-8')
        image = 'test/test'

        docker_config, name, create = App()._get_private_registry_config(image, registry)
        dockerConfig = json.loads(docker_config)
        expected = {"https://index.docker.io/v1/": {"auth": encAuth}}
        self.assertEqual(dockerConfig.get('auths'), expected)
        self.assertEqual(name, "private-registry")
        self.assertEqual(create, True)

        image = "quay.io/test/test"
        docker_config, name, create = App()._get_private_registry_config(image, registry)
        dockerConfig = json.loads(docker_config)
        expected = {"quay.io": {"auth": encAuth}}
        self.assertEqual(dockerConfig.get('auths'), expected)
        self.assertEqual(name, "private-registry")
        self.assertEqual(create, True) 
开发者ID:deis,项目名称:controller,代码行数:22,代码来源:test_app.py

示例11: _create_curl_conn

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def _create_curl_conn(self, url):
        """
        Create a cURL connection object with useful default settings.
        """
        headers = []
        if self.user is not None and self.secret is not None:
            b64cred = base64.b64encode("{}:{}".format(self.user, self.secret))
            headers.append("Authorization: Basic {}".format(b64cred))

        conn = pycurl.Curl()

        if len(headers) > 0:
            conn.setopt(pycurl.HTTPHEADER, headers)

        conn.setopt(pycurl.URL, url)

        # github often redirects
        conn.setopt(pycurl.FOLLOWLOCATION, 1)

        return conn 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:22,代码来源:downloader.py

示例12: get_image

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def get_image(self):
        """
        Get an image from the camera.

        Returns image data as a BytesIO object.
        """
        url = "http://{}/image.jpg".format(self.host)

        encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')

        headers = {
            'Authorization': 'Basic ' + encoded
        }

        result = requests.get(url, headers=headers)
        if result.ok:
            return BytesIO(result.content)

        else:
            return None 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:22,代码来源:camera.py

示例13: make_cloud_mlengine_request_fn

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def make_cloud_mlengine_request_fn(credentials, model_name, version):
  """Wraps function to make CloudML Engine requests with runtime args."""

  def _make_cloud_mlengine_request(examples):
    """Builds and sends requests to Cloud ML Engine."""
    api = discovery.build("ml", "v1", credentials=credentials)
    parent = "projects/%s/models/%s/versions/%s" % (cloud.default_project(),
                                                    model_name, version)
    input_data = {
        "instances": [{
            "input": {
                "b64": base64.b64encode(ex.SerializeToString())
            }
        } for ex in examples]
    }
    prediction = api.projects().predict(body=input_data, name=parent).execute()
    return prediction["predictions"]

  return _make_cloud_mlengine_request 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:21,代码来源:serving_utils.py

示例14: renderWidget

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def renderWidget(chart, width=None, height=None):
    """ Render a pygal chart into a Jupyter Notebook """
    from ipywidgets import HTML

    b64 = base64.b64encode(chart.render()).decode('utf-8')

    src = 'data:image/svg+xml;charset=utf-8;base64,'+b64

    if width and not height:
        html = '<embed src={} width={}></embed>'.format(src, width)
    elif height and not width:
        html = '<embed src={} height={}></embed>'.format(src, height)
    elif width and height:
        html = '<embed src={} height={} width={}></embed>'.format(src,
                                                                  height,
                                                                  width)
    else:
        html = '<embed src={}>'.format(src)

    return HTML(html) 
开发者ID:fitoprincipe,项目名称:ipygee,代码行数:22,代码来源:chart.py

示例15: encrypt_ecb

# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import b64encode [as 别名]
def encrypt_ecb(plain_text, key):
    """
    SM4(ECB)加密
    :param plain_text: 明文
    :param key: 密钥, 小于等于16字节
    """
    plain_text = _padding(plain_text, mode=SM4_ENCRYPT)
    if plain_text is None:
        return

    # 密钥检验
    key = _key_iv_check(key_iv=key)

    plain_hex = _hex(plain_text)
    cipher_hex_list = []
    for i in _range(len(plain_text) // BLOCK_BYTE):
        sub_hex = plain_hex[i * BLOCK_HEX:(i + 1) * BLOCK_HEX]
        cipher = encrypt(clear_num=int(sub_hex, 16),
                         mk=int(_hex(key), 16))
        cipher_hex_list.append(num2hex(num=cipher, width=BLOCK_HEX))

    cipher_text = b64encode(_unhex(''.join(cipher_hex_list)))
    return cipher_text if PY2 else cipher_text.decode(E_FMT) 
开发者ID:yang3yen,项目名称:pysm4,代码行数:25,代码来源:sm4.py


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