python字符串转base64_Python base64.encodestring方法代码示例

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

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

示例1: query

​点赞 6

# 需要导入模块: 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)

开发者ID:aparo,项目名称:awesome-zio,代码行数:21,

示例2: test_http_basic_auth

​点赞 6

# 需要导入模块: 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)

开发者ID:LibraryOfCongress,项目名称:gazetteer,代码行数:18,

示例3: proxy_open

​点赞 6

# 需要导入模块: 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

开发者ID:war-and-code,项目名称:jawfish,代码行数:24,

示例4: data_tag

​点赞 6

# 需要导入模块: 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 ""+da+"\n"

开发者ID:ME-ICA,项目名称:me-ica,代码行数:26,

示例5: query

​点赞 6

# 需要导入模块: 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)

开发者ID:lauris,项目名称:awesome-scala,代码行数:25,

示例6: _validate_header

​点赞 6

# 需要导入模块: 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

开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:19,

示例7: get_auth_header

​点赞 6

# 需要导入模块: 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

开发者ID:grycap,项目名称:im,代码行数:27,

示例8: _encode_auth

​点赞 6

# 需要导入模块: 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','')

开发者ID:jpush,项目名称:jbox,代码行数:23,

示例9: _encode_auth

​点赞 6

# 需要导入模块: 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', '')

开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:23,

示例10: _encode_auth

​点赞 6

# 需要导入模块: 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','')

开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:23,

示例11: _tunnel

​点赞 6

# 需要导入模块: 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

开发者ID:birforce,项目名称:vnpy_crypto,代码行数:27,

示例12: base64_encode

​点赞 6

# 需要导入模块: 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

开发者ID:ktraunmueller,项目名称:Computable,代码行数:18,

示例13: hmac

​点赞 5

# 需要导入模块: 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')

开发者ID:netpieio,项目名称:microgear-python,代码行数:12,

示例14: retry_http_basic_auth

​点赞 5

# 需要导入模块: 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

开发者ID:war-and-code,项目名称:jawfish,代码行数:13,

示例15: encode_base64

​点赞 5

# 需要导入模块: 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'

开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:11,

示例16: represent_binary

​点赞 5

# 需要导入模块: import base64 [as 别名]

# 或者: from base64 import encodestring [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='|')

开发者ID:remg427,项目名称:misp42splunk,代码行数:8,

示例17: encrypt

​点赞 5

# 需要导入模块: import base64 [as 别名]

# 或者: from base64 import encodestring [as 别名]

def encrypt(self, key, msg):

from Crypto.Cipher import AES

secret = self.getSecret(key)

Initial16bytes = '0123456789012345'

cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)

enc = encodestring(cipher.encrypt(self.pad(msg)))

return enc

开发者ID:fangpenlin,项目名称:bugbuzz-python,代码行数:9,

示例18: fetch_page

​点赞 5

# 需要导入模块: import base64 [as 别名]

# 或者: from base64 import encodestring [as 别名]

def fetch_page(self, page):

logging.info("Freshdesk: fetching page %s" % page)

base64string = base64.encodestring('%s:%s' % (self.key, "X")).replace('\n','')

auth = "Basic %s" % base64string

headers = {'Authorization': auth}

r = requests.get(self.endpoint + self.path+str(page), headers = headers)

r.raise_for_status()

try:

return json.loads(r.content)

except Exception:

logging.info("Could not parse json from request content:\n" + r.content)

raise

开发者ID:dataiku,项目名称:dataiku-contrib,代码行数:15,

示例19: base64_string

​点赞 5

# 需要导入模块: import base64 [as 别名]

# 或者: from base64 import encodestring [as 别名]

def base64_string(self):

return base64.encodestring(self.svg.to_string().encode()).replace(b'\n', b'')

开发者ID:bryanveloso,项目名称:geopatterns,代码行数:4,

示例20: _create_sec_websocket_key

​点赞 5

# 需要导入模块: import base64 [as 别名]

# 或者: from base64 import encodestring [as 别名]

def _create_sec_websocket_key():

uid = uuid.uuid4()

return base64.encodestring(uid.bytes).strip()

开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:5,

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值