本文整理匯總了Python中base64.encodestring方法的典型用法代碼示例。如果您正苦於以下問題:Python base64.encodestring方法的具體用法?Python base64.encodestring怎麽用?Python base64.encodestring使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類base64
的用法示例。
在下文中一共展示了base64.encodestring方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: query
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def query(owner, name):
if fake:
print ' {0}/{1}: ok'.format(owner, name)
return (random.randint(1, 1000), random.randint(1, 300))
else:
try:
req = urllib2.Request('https://api.github.com/repos/{0}/{1}'.format(owner, name))
if user is not None and token is not None:
b64 = base64.encodestring('{0}:{1}'.format(user, token)).replace('\n', '')
req.add_header("Authorization", "Basic {0}".format(b64))
u = urllib2.urlopen(req)
j = json.load(u)
t = datetime.datetime.strptime(j['updated_at'], "%Y-%m-%dT%H:%M:%SZ")
days = max(int((now - t).days), 0)
print ' {0}/{1}: ok'.format(owner, name)
return (int(j['stargazers_count']), days)
except urllib2.HTTPError, e:
print ' {0}/{1}: FAILED'.format(owner, name)
return (None, None)
示例2: test_http_basic_auth
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def test_http_basic_auth(self):
def get_auth_string(username, password):
credentials = base64.encodestring('%s:%s' % (username, password)).strip()
auth_string = 'Basic %s' % credentials
return auth_string
correct_creds = get_auth_string(self.test_user.username, self.user_password)
wrong_creds = get_auth_string("wronguser", "wrongpasswrod")
post_json_data= '{"geometry":{},"type":"Feature", "properties":{"importance":null,"feature_code":"PPL","id":null,"population":null, \
"is_composite":true,"name":"New Testing Place3","area":null,"admin":[],"is_primary":true,"alternate":null, \
"timeframe":{},"uris":[]}}'
response = self.c.post('/1.0/place.json', post_json_data, content_type='application/json', HTTP_AUTHORIZATION=wrong_creds)
self.assertEqual(response.status_code, 403)
response = self.c.post('/1.0/place.json', post_json_data, content_type='application/json', HTTP_AUTHORIZATION=correct_creds)
self.assertEqual(response.status_code, 200)
示例3: proxy_open
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def proxy_open(self, req, proxy, type):
orig_type = req.get_type()
type, r_type = splittype(proxy)
host, XXX = splithost(r_type)
if '@' in host:
user_pass, host = host.split('@', 1)
user_pass = base64.encodestring(unquote(user_pass)).strip()
req.add_header('Proxy-Authorization', 'Basic '+user_pass)
host = unquote(host)
req.set_proxy(host, type)
if orig_type == type:
# let other handlers take care of it
# XXX this only makes sense if the proxy is before the
# other handlers
return None
else:
# need to start over, because the other handlers don't
# grok the proxy's URL type
return self.parent.open(req)
# feature suggested by Duncan Booth
# XXX custom is not a good name
示例4: data_tag
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def data_tag(dataarray, encoding, datatype, ordering):
""" Creates the data tag depending on the required encoding """
import base64
import zlib
ord = array_index_order_codes.npcode[ordering]
enclabel = gifti_encoding_codes.label[encoding]
if enclabel == 'ASCII':
c = BytesIO()
# np.savetxt(c, dataarray, format, delimiter for columns)
np.savetxt(c, dataarray, datatype, ' ')
c.seek(0)
da = c.read()
elif enclabel == 'B64BIN':
da = base64.encodestring(dataarray.tostring(ord))
elif enclabel == 'B64GZ':
# first compress
comp = zlib.compress(dataarray.tostring(ord))
da = base64.encodestring(comp)
da = da.decode()
elif enclabel == 'External':
raise NotImplementedError("In what format are the external files?")
else:
da = ''
return "<Data>"+da+"</Data>\n"
示例5: query
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def query(owner, name):
if fake:
print(" {0}/{1}: ok".format(owner, name))
return (random.randint(1, 1000), random.randint(1, 300))
else:
try:
req = urllib2.Request(
"https://api.github.com/repos/{0}/{1}".format(owner, name)
)
if user is not None and token is not None:
b64 = base64.encodestring("{0}:{1}".format(user, token)).replace(
"\n", ""
)
req.add_header("Authorization", "Basic {0}".format(b64))
u = urllib2.urlopen(req)
j = json.load(u)
t = datetime.datetime.strptime(j["updated_at"], "%Y-%m-%dT%H:%M:%SZ")
days = max(int((now - t).days), 0)
print(" {0}/{1}: ok".format(owner, name))
return (int(j["stargazers_count"]), days)
except urllib2.HTTPError as e:
print(" {0}/{1}: FAILED".format(owner, name))
return (None, None)
示例6: _validate_header
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def _validate_header(self, headers, key):
for k, v in _HEADERS_TO_CHECK.iteritems():
r = headers.get(k, None)
if not r:
return False
r = r.lower()
if v != r:
return False
result = headers.get("sec-websocket-accept", None)
if not result:
return False
result = result.lower()
value = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
hashed = base64.encodestring(hashlib.sha1(value).digest()).strip().lower()
return hashed == result
示例7: get_auth_header
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def get_auth_header(self, auth_data):
"""
Generate the auth header needed to contact with the Kubernetes API server.
"""
url = urlparse(self.cloud.server)
auths = auth_data.getAuthInfo(self.type, url[1])
if not auths:
self.log_error(
"No correct auth data has been specified to Kubernetes.")
return None
else:
auth = auths[0]
auth_header = None
if 'username' in auth and 'password' in auth:
passwd = auth['password']
user = auth['username']
auth_header = {'Authorization': 'Basic ' +
(base64.encodestring((user + ':' + passwd).encode('utf-8'))).strip().decode('utf-8')}
elif 'token' in auth:
token = auth['token']
auth_header = {'Authorization': 'Bearer ' + token}
return auth_header
示例8: _encode_auth
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:' + 'password'*10
>>> chr(10) in str(_encode_auth(long_auth))
False
"""
auth_s = urllib.parse.unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
# use the legacy interface for Python 2.3 support
encoded_bytes = base64.encodestring(auth_bytes)
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
return encoded.replace('\n','')
示例9: _encode_auth
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:' + 'password'*10
>>> chr(10) in str(_encode_auth(long_auth))
False
"""
auth_s = urllib.parse.unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
# use the legacy interface for Python 2.3 support
encoded_bytes = base64.encodestring(auth_bytes)
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
return encoded.replace('\n', '')
示例10: _encode_auth
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:' + 'password'*10
>>> chr(10) in str(_encode_auth(long_auth))
False
"""
auth_s = unquote(auth)
# convert to bytes
auth_bytes = auth_s.encode()
# use the legacy interface for Python 2.3 support
encoded_bytes = base64.encodestring(auth_bytes)
# convert back to a string
encoded = encoded_bytes.decode()
# strip the trailing carriage return
return encoded.replace('\n','')
示例11: _tunnel
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [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
示例12: base64_encode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def base64_encode(nb):
"""Base64 encode all bytes objects in the notebook.
These will be b64-encoded unicode strings
Note: This is never used
"""
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
for output in cell.outputs:
if 'png' in output:
output.png = encodestring(output.png).decode('ascii')
if 'jpeg' in output:
output.jpeg = encodestring(output.jpeg).decode('ascii')
return nb
示例13: hmac
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def hmac(key, message):
import base64
import hmac
import hashlib
hash = hmac.new(key.encode('utf-8'),message.encode('utf-8'), hashlib.sha1).digest()
password = base64.encodestring(hash)
password = password.strip()
return password.decode('utf-8')
示例14: retry_http_basic_auth
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [as 別名]
def retry_http_basic_auth(self, host, req, realm):
user,pw = self.passwd.find_user_password(realm, host)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.encodestring(raw).strip()
if req.headers.get(self.auth_header, None) == auth:
return None
req.add_header(self.auth_header, auth)
return self.parent.open(req)
else:
return None
示例15: encode_base64
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import encodestring [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'