需要導入模塊: import codecs [as 別名] # 或者: from codecs import encode [as 別名] def macaroon(self): """ try to open the macaroon and return it as a byte ...
當前位置:首頁>>代碼示例>>Python>>正文
本文整理匯總了Python中codecs.encode方法的典型用法代碼示例。
如果您正苦於以下問題:Pythoncodecs.encode方法的具體用法?Pythoncodecs.encode怎麽用?Pythoncodecs.encode使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。
您也可以進一步了解該方法所在類codecs的用法示例。
在下文中一共展示了codecs.encode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。
您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1:macaroon
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defmacaroon(self):
"""
trytoopenthemacaroonandreturnitasabytestring
"""
try:
withopen(self.macaroon_path,"rb")asf:
macaroon_bytes=f.read()
macaroon=codecs.encode(macaroon_bytes,"hex")
returnmacaroon
exceptFileNotFoundError:
sys.stderr.write(
f"Couldnotfindmacaroonin{self.macaroon_path}.Thismighthappen"
f"inversionsoflnd0:
print("error='PAYMENTFAILED'")
print("error_detail='{}'".format(response.payment_error))
return
exceptExceptionase:
print("error='FAILEDLNDINVOICEPAYMENT'")
return
returnresponse開發者ID:rootzoll,項目名稱:raspiblitz,代碼行數:27,代碼來源:blitz.ip2tor.py
示例4:__init__
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
def__init__(self):
global_all_handles
#Generatelabeloftext/unicodetypefromthreerandombytes.
self._id=codecs.encode(os.urandom(3),"hex_codec").decode("ascii")
self._legit_pid=os.getpid()
self._make_nonblocking()
#Definelockforsynchronizingaccesstothishandlewithinthecurrent
#process.Notethata`gevent.lock.Semaphore`instancelivesonthe
#heapofthecurrentprocessandcannotbeusedtosynchronizeaccess
#acrossmultipleprocesses.Thatis,thislockisonlymeaningfulin
#thecurrentprocess.Thisisespeciallyimportanttoconsiderwhenthe
#platformsupportsfork()ing.
self._lock=gevent.lock.Semaphore(value=1)
self._closed=False
_all_handles.append(self)開發者ID:jgehrcke,項目名稱:gipc,代碼行數:18,代碼來源:gipc.py
示例5:pbkdf2_hex
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defpbkdf2_hex(
data,salt,iterations=DEFAULT_PBKDF2_ITERATIONS,keylen=None,hashfunc=None
):
"""Like:func:`pbkdf2_bin`,butreturnsahex-encodedstring.
..versionadded::0.9
:paramdata:thedatatoderive.
:paramsalt:thesaltforthederivation.
:paramiterations:thenumberofiterations.
:paramkeylen:thelengthoftheresultingkey.Ifnotprovided,
thedigestsizewillbeused.
:paramhashfunc:thehashfunctiontouse.Thiscaneitherbethe
stringnameofaknownhashfunction,orafunction
fromthehashlibmodule.Defaultstosha256.
"""
rv=pbkdf2_bin(data,salt,iterations,keylen,hashfunc)
returnto_native(codecs.encode(rv,"hex_codec"))開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:security.py
示例6:make_dokuwiki_pagename
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defmake_dokuwiki_pagename(mediawiki_name):
"""
Convertacanonicalmediawikipagenametoadokuwikipagename
Anynamespacingthatisintheformofa/isreplacedwitha:
"""
result=mediawiki_name.replace("","_")
#Wehavepagesthathave':'inthem-replacewithunderscores
result=result.replace(':','_')
result=names.clean_id(camel_to_underscore(result)).replace("/",":")
#Someofourmediawikipagenamesbeginwitha'/',whichresultsinos.path.joinassumingthepageisanabsolutepath.
ifresult[0]==':':
result=result.lstrip(':')
#Fixanypagesthatbeganwithaspace,becausethatbreaksdokuwiki
result=result.replace(":_",":")
result=codecs.encode(result,sys.getfilesystemencoding(),"replace")
returnresult開發者ID:projectgus,項目名稱:yamdwe,代碼行數:19,代碼來源:dokuwiki.py
示例7:pbkdf2_hex
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defpbkdf2_hex(data,salt,iterations=DEFAULT_PBKDF2_ITERATIONS,
keylen=None,hashfunc=None):
"""Like:func:`pbkdf2_bin`,butreturnsahex-encodedstring.
..versionadded::0.9
:paramdata:thedatatoderive.
:paramsalt:thesaltforthederivation.
:paramiterations:thenumberofiterations.
:paramkeylen:thelengthoftheresultingkey.Ifnotprovided,
thedigestsizewillbeused.
:paramhashfunc:thehashfunctiontouse.Thiscaneitherbethe
stringnameofaknownhashfunction,orafunction
fromthehashlibmodule.Defaultstosha1.
"""
rv=pbkdf2_bin(data,salt,iterations,keylen,hashfunc)
returnto_native(codecs.encode(rv,'hex_codec'))開發者ID:jpush,項目名稱:jbox,代碼行數:19,代碼來源:security.py
示例8:_maskStrings
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
def_maskStrings(self,macroLines,newFunctionName):
"""MaskstringinVBAbyencodingthem"""
#Findstringsandreplacethembyhexencodedversion
forn,lineinenumerate(macroLines):
#Checkifstringisnotpreprocessorinstruction,constorcontainescapequoting
ifline.lstrip()!=""andline.lstrip()[0]!='#'and"Const"notinlineand"\"\""notinlineand"PtrSafeFunction"notinlineand"DeclareFunction"notinlineand"PtrSafeSub"notinlineand"DeclareSub"notinlineand"Environ"notinline:
#Findstringsinline
findList=re.findall(r'"(.+?)"',line,re.I)
iffindList:
fordetectedStringinfindList:
#Hexencodestring
encodedBytes=codecs.encode(bytes(detectedString,"utf-8"),'hex_codec')
newStr=newFunctionName+"(\""+encodedBytes.decode("utf-8")+"\")"
wordToReplace="\""+detectedString+"\""
line=line.replace(wordToReplace,newStr)
#Replacelineifresultisnottoobig
iflen(line)<1024:
macroLines[n]=line
returnmacroLines開發者ID:sevagas,項目名稱:macro_pack,代碼行數:22,代碼來源:obfuscate_strings.py
示例9:seal_aes_ctr_legacy
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defseal_aes_ctr_legacy(key_service,secret,digest_method=DEFAULT_DIGEST):
"""
Encrypts`secret`usingthekeyservice.
Youcandecryptwiththecompanionmethod`open_aes_ctr_legacy`.
"""
#generateaa64bytekey.
#Halfwillbefordataencryption,theotherhalfforHMAC
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,
}開發者ID:fugue,項目名稱:credstash,代碼行數:19,代碼來源:credstash.py
示例10:benchmark
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defbenchmark(n):
globalmethods
if'--onlyself'insys.argv[1:]:
methods=[mforminmethodsifm[0].startswith("tabulate")]
else:
methods=methods
results=[(desc,timeit(code,setup_code,number=n)/n*1e6)
fordesc,codeinmethods]
mintime=min(map(lambdax:x[1],results))
results=[(desc,t,t/mintime)fordesc,tin
sorted(results,key=lambdax:x[1])]
table=tabulate.tabulate(results,
[u"Tableformatter",u"time,μs",u"rel.time"],
u"rst",floatfmt=".1f")
printcodecs.encode(table,"utf-8")開發者ID:gregbanks,項目名稱:python-tabulate,代碼行數:18,代碼來源:benchmark.py
示例11:pbkdf2_hex
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defpbkdf2_hex(data,salt,iterations=DEFAULT_PBKDF2_ITERATIONS,
keylen=None,hashfunc=None):
"""Like:func:`pbkdf2_bin`,butreturnsahex-encodedstring.
..versionadded::0.9
:paramdata:thedatatoderive.
:paramsalt:thesaltforthederivation.
:paramiterations:thenumberofiterations.
:paramkeylen:thelengthoftheresultingkey.Ifnotprovided,
thedigestsizewillbeused.
:paramhashfunc:thehashfunctiontouse.Thiscaneitherbethe
stringnameofaknownhashfunction,orafunction
fromthehashlibmodule.Defaultstosha256.
"""
rv=pbkdf2_bin(data,salt,iterations,keylen,hashfunc)
returnto_native(codecs.encode(rv,'hex_codec'))開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:19,代碼來源:security.py
示例12:test_bug1098990_b
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
deftest_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"")開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_codecs.py
示例13:test_ascii
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
deftest_ascii(self):
#SetD(directlyencodedcharacters)
set_d=('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789'
'\'(),-./:?')
self.assertEqual(set_d.encode(self.encoding),set_d)
self.assertEqual(set_d.decode(self.encoding),set_d)
#SetO(optionaldirectcharacters)
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')
#Whitespaces
ws='\t\n\r'
self.assertEqual(ws.encode(self.encoding),ws)
self.assertEqual(ws.decode(self.encoding),ws)
#OtherASCIIcharacters
other_ascii=''.join(sorted(set(chr(i)foriinrange(0x80))-
set(set_d+set_o+'+'+ws)))
self.assertEqual(other_ascii.encode(self.encoding),
'+AAAAAQACAAMABAAFAAYABwAIAAsADAAOAA8AEAARABIAEwAU'
'ABUAFgAXABgAGQAaABsAHAAdAB4AHwBcAH4Afw-')開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:27,代碼來源:test_codecs.py
示例14:test_all
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
deftest_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__))
forapiincodecs.__all__:
getattr(codecs,api)開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:23,代碼來源:test_codecs.py
示例15:random
▲點讚6
▼
#需要導入模塊:importcodecs[as別名]
#或者:fromcodecsimportencode[as別名]
defrandom(cls,length):
#type:(int)->TryteString
"""
Generatesarandomsequenceoftrytes.
:paramlength:
Numberoftrytestogenerate.
"""
alphabet=list(itervalues(AsciiTrytesCodec.alphabet))
generator=SystemRandom()
#:py:meth:`SystemRandom.choices`wasn'taddeduntilPython3.6;
#forcompatibility,wewillcontinuetouse``choice``inaloop.
#https://docs.python.org/3/library/random.html#random.choices
returncls(
''.join(chr(generator.choice(alphabet))for_inrange(length))
.encode('ascii')
)開發者ID:llSourcell,項目名稱:IOTA_demo,代碼行數:20,代碼來源:types.py
注:本文中的codecs.encode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。