本文整理汇总了Python中codecs.encode方法的典型用法代码示例。如果您正苦于以下问题:Python codecs.encode方法的具体用法?Python codecs.encode怎么用?Python codecs.encode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类codecs
的用法示例。
在下文中一共展示了codecs.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: macaroon
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def macaroon(self):
"""
try to open the macaroon and return it as a byte string
"""
try:
with open(self.macaroon_path, "rb") as f:
macaroon_bytes = f.read()
macaroon = codecs.encode(macaroon_bytes, "hex")
return macaroon
except FileNotFoundError:
sys.stderr.write(
f"Could not find macaroon in {self.macaroon_path}. This might happen"
f"in versions of lnd < v0.5-beta or those not using default"
f"installation path. Set client object's macaroon_path attribute"
f"manually."
)
示例2: lndDecodeInvoice
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def lndDecodeInvoice(lnInvoiceString):
try:
# call LND GRPC API
macaroon = codecs.encode(open(LND_ADMIN_MACAROON_PATH, 'rb').read(), 'hex')
os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
cert = open(LND_TLS_PATH, 'rb').read()
ssl_creds = grpc.ssl_channel_credentials(cert)
channel = grpc.secure_channel("{0}:10009".format(LND_IP), ssl_creds)
stub = rpcstub.LightningStub(channel)
request = lnrpc.PayReqString(
pay_req=lnInvoiceString,
)
response = stub.DecodePayReq(request, metadata=[('macaroon', macaroon)])
# validate results
if response.num_msat <= 0:
print("error='ZERO INVOICES NOT ALLOWED'")
return
except Exception as e:
print("error='FAILED LND INVOICE DECODING'")
return
return response
示例3: lndPayInvoice
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def lndPayInvoice(lnInvoiceString):
try:
# call LND GRPC API
macaroon = codecs.encode(open(LND_ADMIN_MACAROON_PATH, 'rb').read(), 'hex')
os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
cert = open(LND_TLS_PATH, 'rb').read()
ssl_creds = grpc.ssl_channel_credentials(cert)
channel = grpc.secure_channel("{0}:10009".format(LND_IP), ssl_creds)
stub = rpcstub.LightningStub(channel)
request = lnrpc.SendRequest(
payment_request=lnInvoiceString,
)
response = stub.SendPaymentSync(request, metadata=[('macaroon', macaroon)])
# validate results
if len(response.payment_error) > 0:
print("error='PAYMENT FAILED'")
print("error_detail='{}'".format(response.payment_error))
return
except Exception as e:
print("error='FAILED LND INVOICE PAYMENT'")
return
return response
示例4: __init__
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def __init__(self):
global _all_handles
# Generate label of text/unicode type from three random bytes.
self._id = codecs.encode(os.urandom(3), "hex_codec").decode("ascii")
self._legit_pid = os.getpid()
self._make_nonblocking()
# Define lock for synchronizing access to this handle within the current
# process. Note that a `gevent.lock.Semaphore` instance lives on the
# heap of the current process and cannot be used to synchronize access
# across multiple processes. That is, this lock is only meaningful in
# the current process. This is especially important to consider when the
# platform supports fork()ing.
self._lock = gevent.lock.Semaphore(value=1)
self._closed = False
_all_handles.append(self)
示例5: pbkdf2_hex
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def pbkdf2_hex(
data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None
):
"""Like :func:`pbkdf2_bin`, but returns a hex-encoded string.
.. versionadded:: 0.9
:param data: the data to derive.
:param salt: the salt for the derivation.
:param iterations: the number of iterations.
:param keylen: the length of the resulting key. If not provided,
the digest size will be used.
:param hashfunc: the hash function to use. This can either be the
string name of a known hash function, or a function
from the hashlib module. Defaults to sha256.
"""
rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)
return to_native(codecs.encode(rv, "hex_codec"))
示例6: make_dokuwiki_pagename
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def make_dokuwiki_pagename(mediawiki_name):
"""
Convert a canonical mediawiki pagename to a dokuwiki pagename
Any namespacing that is in the form of a / is replaced with a :
"""
result = mediawiki_name.replace(" ","_")
# We have pages that have ':' in them - replace with underscores
result = result.replace(':', '_')
result = names.clean_id(camel_to_underscore(result)).replace("/",":")
# Some of our mediawiki page names begin with a '/', which results in os.path.join assuming the page is an absolute path.
if result[0] == ':':
result = result.lstrip(':')
# Fix any pages that began with a space, because that breaks dokuwiki
result = result.replace(":_", ":")
result = codecs.encode(result, sys.getfilesystemencoding(), "replace")
return result
示例7: pbkdf2_hex
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,
keylen=None, hashfunc=None):
"""Like :func:`pbkdf2_bin`, but returns a hex-encoded string.
.. versionadded:: 0.9
:param data: the data to derive.
:param salt: the salt for the derivation.
:param iterations: the number of iterations.
:param keylen: the length of the resulting key. If not provided,
the digest size will be used.
:param hashfunc: the hash function to use. This can either be the
string name of a known hash function, or a function
from the hashlib module. Defaults to sha1.
"""
rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)
return to_native(codecs.encode(rv, 'hex_codec'))
示例8: _maskStrings
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def _maskStrings(self,macroLines, newFunctionName):
""" Mask string in VBA by encoding them """
# Find strings and replace them by hex encoded version
for n,line in enumerate(macroLines):
#Check if string is not preprocessor instruction, const or contain escape quoting
if line.lstrip() != "" and line.lstrip()[0] != '#' and "Const" not in line and "\"\"" not in line and "PtrSafe Function" not in line and "Declare Function" not in line and "PtrSafe Sub" not in line and "Declare Sub" not in line and "Environ" not in line:
# Find strings in line
findList = re.findall( r'"(.+?)"', line, re.I)
if findList:
for detectedString in findList:
# Hex encode string
encodedBytes = codecs.encode(bytes(detectedString, "utf-8"), 'hex_codec')
newStr = newFunctionName + "(\"" + encodedBytes.decode("utf-8") + "\")"
wordToReplace = "\"" + detectedString + "\""
line = line.replace(wordToReplace, newStr)
# Replace line if result is not too big
if len(line) < 1024:
macroLines[n] = line
return macroLines
示例9: seal_aes_ctr_legacy
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
"""
Encrypts `secret` using the key service.
You can decrypt with the companion method `open_aes_ctr_legacy`.
"""
# generate a a 64 byte key.
# Half will be for data encryption, the other half for HMAC
key, encoded_key = key_service.generate_key_data(64)
ciphertext, hmac = _seal_aes_ctr(
secret, key, LEGACY_NONCE, digest_method,
)
return {
'key': b64encode(encoded_key).decode('utf-8'),
'contents': b64encode(ciphertext).decode('utf-8'),
'hmac': codecs.encode(hmac, "hex_codec"),
'digest': digest_method,
}
示例10: benchmark
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def benchmark(n):
global methods
if '--onlyself' in sys.argv[1:]:
methods = [ m for m in methods if m[0].startswith("tabulate") ]
else:
methods = methods
results = [(desc, timeit(code, setup_code, number=n)/n * 1e6)
for desc, code in methods]
mintime = min(map(lambda x: x[1], results))
results = [(desc, t, t/mintime) for desc, t in
sorted(results, key=lambda x: x[1])]
table = tabulate.tabulate(results,
[u"Table formatter", u"time, μs", u"rel. time"],
u"rst", floatfmt=".1f")
print codecs.encode(table, "utf-8")
示例11: pbkdf2_hex
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,
keylen=None, hashfunc=None):
"""Like :func:`pbkdf2_bin`, but returns a hex-encoded string.
.. versionadded:: 0.9
:param data: the data to derive.
:param salt: the salt for the derivation.
:param iterations: the number of iterations.
:param keylen: the length of the resulting key. If not provided,
the digest size will be used.
:param hashfunc: the hash function to use. This can either be the
string name of a known hash function, or a function
from the hashlib module. Defaults to sha256.
"""
rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)
return to_native(codecs.encode(rv, 'hex_codec'))
示例12: test_bug1098990_b
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def test_bug1098990_b(self):
s1 = u"aaaaaaaaaaaaaaaaaaaaaaaa\r\n"
s2 = u"bbbbbbbbbbbbbbbbbbbbbbbb\r\n"
s3 = u"stillokay:bbbbxx\r\n"
s4 = u"broken!!!!badbad\r\n"
s5 = u"againokay.\r\n"
s = (s1+s2+s3+s4+s5).encode(self.encoding)
stream = StringIO.StringIO(s)
reader = codecs.getreader(self.encoding)(stream)
self.assertEqual(reader.readline(), s1)
self.assertEqual(reader.readline(), s2)
self.assertEqual(reader.readline(), s3)
self.assertEqual(reader.readline(), s4)
self.assertEqual(reader.readline(), s5)
self.assertEqual(reader.readline(), u"")
示例13: test_ascii
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def test_ascii(self):
# Set D (directly encoded characters)
set_d = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789'
'\'(),-./:?')
self.assertEqual(set_d.encode(self.encoding), set_d)
self.assertEqual(set_d.decode(self.encoding), set_d)
# Set O (optional direct characters)
set_o = ' !"#$%&*;<=>@[]^_`{|}'
self.assertEqual(set_o.encode(self.encoding), set_o)
self.assertEqual(set_o.decode(self.encoding), set_o)
# +
self.assertEqual(u'a+b'.encode(self.encoding), 'a+-b')
self.assertEqual('a+-b'.decode(self.encoding), u'a+b')
# White spaces
ws = ' \t\n\r'
self.assertEqual(ws.encode(self.encoding), ws)
self.assertEqual(ws.decode(self.encoding), ws)
# Other ASCII characters
other_ascii = ''.join(sorted(set(chr(i) for i in range(0x80)) -
set(set_d + set_o + '+' + ws)))
self.assertEqual(other_ascii.encode(self.encoding),
'+AAAAAQACAAMABAAFAAYABwAIAAsADAAOAA8AEAARABIAEwAU'
'ABUAFgAXABgAGQAaABsAHAAdAB4AHwBcAH4Afw-')
示例14: test_all
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def test_all(self):
api = (
"encode", "decode",
"register", "CodecInfo", "Codec", "IncrementalEncoder",
"IncrementalDecoder", "StreamReader", "StreamWriter", "lookup",
"getencoder", "getdecoder", "getincrementalencoder",
"getincrementaldecoder", "getreader", "getwriter",
"register_error", "lookup_error",
"strict_errors", "replace_errors", "ignore_errors",
"xmlcharrefreplace_errors", "backslashreplace_errors",
"open", "EncodedFile",
"iterencode", "iterdecode",
"BOM", "BOM_BE", "BOM_LE",
"BOM_UTF8", "BOM_UTF16", "BOM_UTF16_BE", "BOM_UTF16_LE",
"BOM_UTF32", "BOM_UTF32_BE", "BOM_UTF32_LE",
"BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE", # Undocumented
"StreamReaderWriter", "StreamRecoder",
)
self.assertEqual(sorted(api), sorted(codecs.__all__))
for api in codecs.__all__:
getattr(codecs, api)
示例15: random
# 需要导入模块: import codecs [as 别名]
# 或者: from codecs import encode [as 别名]
def random(cls, length):
# type: (int) -> TryteString
"""
Generates a random sequence of trytes.
:param length:
Number of trytes to generate.
"""
alphabet = list(itervalues(AsciiTrytesCodec.alphabet))
generator = SystemRandom()
# :py:meth:`SystemRandom.choices` wasn't added until Python 3.6;
# for compatibility, we will continue to use ``choice`` in a loop.
# https://docs.python.org/3/library/random.html#random.choices
return cls(
''.join(chr(generator.choice(alphabet)) for _ in range(length))
.encode('ascii')
)