本文整理匯總了Python中base64.encodebytes方法的典型用法代碼示例。如果您正苦於以下問題:Python base64.encodebytes方法的具體用法?Python base64.encodebytes怎麽用?Python base64.encodebytes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類base64
的用法示例。
在下文中一共展示了base64.encodebytes方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_host_info
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def get_host_info(self, host):
x509 = {}
if isinstance(host, tuple):
host, x509 = host
auth, host = urllib_parse.splituser(host)
if auth:
auth = urllib_parse.unquote_to_bytes(auth)
auth = base64.encodebytes(auth).decode("utf-8")
auth = "".join(auth.split()) # get rid of whitespace
extra_headers = [
("Authorization", "Basic " + auth)
]
else:
extra_headers = []
return host, extra_headers, x509
##
# Connect to server.
#
# @param host Target host.
# @return An HTTPConnection object
示例2: _get_login_headers
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def _get_login_headers(self):
session_response = self.mc_afee_request.make_json_request("POST", "session.php", headers={
"Accept": "application/vnd.ve.v1.0+json",
"Content-Type": "application/json",
"VE-SDK-API": base64.encodebytes(
f"{self.username}:{self.password}".encode()
).decode("utf-8").rstrip()
})
if session_response.get("success", False):
session = session_response.get("results", {}).get("session")
user_id = session_response.get("results", {}).get("userId")
return {
"Accept": "application/vnd.ve.v1.0+json",
"VE-SDK-API": base64.encodebytes(
f"{session}:{user_id}".encode()
).decode("utf-8").rstrip()
}
raise ConnectionTestException(ConnectionTestException.Preset.USERNAME_PASSWORD)
示例3: _read_file
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def _read_file(self, blob, format):
"""Reads a non-notebook file.
blob: instance of :class:`google.cloud.storage.Blob`.
format:
If "text", the contents will be decoded as UTF-8.
If "base64", the raw bytes contents will be encoded as base64.
If not specified, try to decode as UTF-8, and fall back to base64
"""
bcontent = blob.download_as_string()
if format is None or format == "text":
# Try to interpret as unicode if format is unknown or if unicode
# was explicitly requested.
try:
return bcontent.decode("utf8"), "text"
except UnicodeError:
if format == "text":
raise web.HTTPError(
400, "%s is not UTF-8 encoded" %
self._get_blob_path(blob),
reason="bad format",
)
return base64.encodebytes(bcontent).decode("ascii"), "base64"
示例4: _tunnel
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def _tunnel(sock, host, port, auth):
debug("Connecting proxy...")
connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
# TODO: support digest auth.
if auth and auth[0]:
auth_str = auth[0]
if auth[1]:
auth_str += ":" + auth[1]
encoded_str = base64encode(auth_str.encode()).strip().decode()
connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
connect_header += "\r\n"
dump("request header", connect_header)
send(sock, connect_header)
try:
status, resp_headers, status_message = read_headers(sock)
except Exception as e:
raise WebSocketProxyException(str(e))
if status != 200:
raise WebSocketProxyException(
"failed CONNECT via proxy status: %r" % status)
return sock
示例5: generate_md5_hash
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def generate_md5_hash(src, block_size=BLOCK_SIZE_BYTES):
checksum = hashlib.md5()
with open(str(src), 'rb') as f:
# Incrementally read data and update the digest
while True:
read_data = f.read(block_size)
if not read_data:
break
checksum.update(read_data)
# Once we have all the data, compute checksum
checksum = checksum.digest()
# Convert into a bytes type that can be base64 encoded
base64_md5 = base64.encodebytes(checksum).decode('UTF-8').strip()
# Print the Base64 encoded CRC32C
return base64_md5
示例6: grab_frame
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def grab_frame(self, **savefig_kwargs):
if self.embed_frames:
# Just stop processing if we hit the limit
if self._hit_limit:
return
f = BytesIO()
self.fig.savefig(f, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
self._total_bytes += len(imgdata64)
if self._total_bytes >= self._bytes_limit:
_log.warning(
"Animation size has reached %s bytes, exceeding the limit "
"of %s. If you're sure you want a larger animation "
"embedded, set the animation.embed_limit rc parameter to "
"a larger value (in MB). This and further frames will be "
"dropped.", self._total_bytes, self._bytes_limit)
self._hit_limit = True
else:
self._saved_frames.append(imgdata64)
else:
return super().grab_frame(**savefig_kwargs)
示例7: get_topology_path_img
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def get_topology_path_img(self, sources='0.0.0.0', destinations='0.0.0.0', services='ANY', url_params=None):
"""
:param sources: comma separated list of source addresses e.g. 1.1.1.0:24
:param destinations: comma separated list of destination addresses
:param services: comma separated list of services
:param url_params:
:return: base64 string
"""
logger.debug("sources={}, destinations={}, services={}, url_params={}".format(
sources, destinations, services, url_params))
if not url_params:
url_params = ""
else:
param_builder = URLParamBuilderDict(url_params)
url_params = param_builder.build(prepend_question_mark=False)
src = ",".join(sources) if isinstance(sources, (list, tuple, set)) else sources
dst = ",".join(destinations) if isinstance(destinations, (list, tuple, set)) else destinations
srv = ",".join(services) if isinstance(services, (list, tuple, set)) else services
uri = "/securetrack/api/topology/path_image?src={}&dst={}&service={}&{}".format(src, dst, srv, url_params)
try:
img = self.get_uri(uri, expected_status_codes=200).response.content
except RequestException as error:
raise IOError("Failed to securetrack configuration. Error: {}".format(error))
return base64.encodebytes(img)
示例8: offload_state
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def offload_state(self) -> Dict[str, str]:
"""
Return serialized state.
:return state_dict:
serialized state that can be used in json.dumps
"""
byte_arr = io.BytesIO()
image = self.get_image()
image.save(byte_arr, format="JPEG")
serialized = base64.encodebytes(byte_arr.getvalue()).decode("utf-8")
return {
"image_id": self.get_image_id(),
"image_location_id": self.get_image_location_id(),
"image": serialized,
}
示例9: test_encodebytes
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def test_encodebytes(self):
eq = self.assertEqual
eq(base64.encodebytes(b"www.python.org"), b"d3d3LnB5dGhvbi5vcmc=\n")
eq(base64.encodebytes(b"a"), b"YQ==\n")
eq(base64.encodebytes(b"ab"), b"YWI=\n")
eq(base64.encodebytes(b"abc"), b"YWJj\n")
eq(base64.encodebytes(b""), b"")
eq(base64.encodebytes(b"abcdefghijklmnopqrstuvwxyz"
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b"0123456789!@#0^&*();:<>,. []{}"),
b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n")
# Non-bytes
eq(base64.encodebytes(bytearray(b'abc')), b'YWJj\n')
eq(base64.encodebytes(memoryview(b'abc')), b'YWJj\n')
eq(base64.encodebytes(array('B', b'abc')), b'YWJj\n')
self.check_type_errors(base64.encodebytes)
示例10: __init__
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def __init__(self, endpoint, namespace, api_key=None, auth=None, insecure=False, user_agent=None):
"""
OpenWhiskClient Constructor
:param endpoint: OpenWhisk endpoint.
:param namespace: User namespace.
:param api_key: User AUTH Key. HTTP Basic authentication.
:param auth: Authorization token string "Basic eyJraWQiOiIyMDE5MDcyNCIsImFsZ...".
:param insecure: Insecure backend. Disable cert verification.
:param user_agent: User agent on requests.
"""
self.endpoint = endpoint.replace('http:', 'https:')
self.namespace = namespace
self.api_key = api_key
self.auth = auth
if self.api_key:
api_key = str.encode(self.api_key)
auth_token = base64.encodebytes(api_key).replace(b'\n', b'')
self.auth = 'Basic %s' % auth_token.decode('UTF-8')
self.session = requests.session()
if insecure:
self.session.verify = False
self.headers = {
'content-type': 'application/json',
'Authorization': self.auth,
}
if user_agent:
default_user_agent = self.session.headers['User-Agent']
self.headers['User-Agent'] = default_user_agent + ' {}'.format(user_agent)
self.session.headers.update(self.headers)
adapter = requests.adapters.HTTPAdapter()
self.session.mount('https://', adapter)
示例11: encode_base64
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def encode_base64(msg):
"""Encode the message's payload in Base64.
Also, add an appropriate Content-Transfer-Encoding header.
"""
orig = msg.get_payload()
encdata = str(_bencode(orig), 'ascii')
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'base64'
示例12: encode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def encode(self, out):
out.write("<value><base64>\n")
encoded = base64.encodebytes(self.data)
out.write(encoded.decode('ascii'))
out.write("</base64></value>\n")
示例13: dump_bytes
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def dump_bytes(self, value, write):
write("<value><base64>\n")
encoded = base64.encodebytes(value)
write(encoded.decode('ascii'))
write("</base64></value>\n")
示例14: __init__
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def __init__(self, repo_name=None):
self.repo_name = repo_name
self.credentials = load_credentials()
self.base_url = self.credentials['artifactory_url']
self.artifactory = party.Party()
if not self.base_url.endswith('/api'):
self.api_url = '/'.join([self.base_url, 'api'])
else:
self.api_url = self.base_url
self.artifactory.artifactory_url = self.api_url
self.artifactory.username = self.credentials['artifactory_username']
self.artifactory.password = base64.encodebytes(bytes(self.credentials['artifactory_password'], 'utf-8'))
self.artifactory.certbundle = os.getenv('LAVATORY_CERTBUNDLE_PATH', certifi.where())
示例15: represent_binary
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodebytes [as 別名]
def represent_binary(self, data):
if hasattr(base64, 'encodebytes'):
data = base64.encodebytes(data).decode('ascii')
else:
data = base64.encodestring(data).decode('ascii')
return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|')