Codecs are responsible for decoding a bytestring into a Document instance, ... require a method of discovering which codecs are installed on the system.
Togglenavigation
CoreAPI-PythonClient
Home
APIGuide
Clients
Documents
Codecs
Transports
Exceptions
Utilities
Topics
ReleaseNotes
Search
Previous
Next
GitHub
Codecs
Usingacodec
Availablecodecs
Customcodecs
Externalpackages
Codecs
CodecsareresponsiblefordecodingabytestringintoaDocumentinstance,
orforencodingaDocumentinstanceintoabytestring.
Acodecisassociatedwithamediatype.ForexampleinHTTPresponses,
theContent-Typeheaderisusedtoindicatethemediatypeof
thebytestringreturnedinthebodyoftheresponse.
WhenusingaCoreAPIclient,HTTPresponsesaredecodedwithanappropriate
codec,basedontheContent-Typeoftheresponse.
Usingacodec
Allthecodecsprovidedbythecoreapilibraryareinstantiatedwithout
arguments,forexample:
fromcoreapiimportcodecs
codec=codecs.CoreJSONCodec()
Acodecwillprovideeitheroneorbothofthedecode()orencode()methods.
Decoding
Signature:decode(bytestring,**options)
Givenabytestring,returnsadecodedDocument,Error,orrawdata.
Anexampleofdecodingadocument:
bytestring=open('document.corejson','rb').read()
document=codec.decode(bytestring)
Theavailableoptionskeywordsdependonthecodec.
Encoding
Signature:encode(document,**options)
GivenaDocumentorError,returnanencodedrepresentationasabytestring.
Anexampleofencodingadocument:
bytestring=codec.encode(document)
output=open('document.corejson','wb')
output.write(bytestring)
output.close()
Theavailableoptionskeywordsdependonthecodec.
Attributes
Thefollowingattributeisavailableoncodecinstances:
media_type-Astringindicatingthemediatypethatthecodecrepresents.
Availablecodecs
CoreJSONCodec
SupportsdecodingorencodingtheCoreJSONformat.
.media_type:application/coreapi+json
.format:openapi
ExampleofdecodingaCoreJSONbytestringintoaDocumentinstance:
>>>fromcoreapiimportcodecs
>>>codec=codecs.CoreJSONCodec()
>>>content=b'{"_type":"document",...}'
>>>document=codec.decode(content)
>>>print(document)
'search':link(from,to,date)
ExampleofencodingaDocumentinstanceintoaCoreJSONbytestring:
>>>content=codec.encode(document,indent=True)
>>>print(content)
{
"_type":"document"
}
Encodingoptions
indent:SettoTrueforanindentedrepresentation.Thedefaultistogenerateacompactrepresentation.
Decodingoptions
base_url:TheURLfromwhichthedocumentwasretrieved.Usedtoresolveanyrelative
URLsinthedocument.
JSONCodec
SupportsdecodingJSONdata.
.media_type:application/json
.format:json
Example:
>>>fromcoreapiimportcodecs
>>>codec=codecs.JSONCodec()
>>>content=b'{"string":"abc","boolean":true,"null":null}'
>>>data=codec.decode(content)
>>>print(data)
{"string":"abc","boolean":True,"null":None}
TextCodec
Supportsdecodingplain-textresponses.
.media_type:text/*
.format:text
Example:
>>>fromcoreapiimportcodecs
>>>codec=codecs.TextCodec()
>>>data=codec.decode(b'hello,world!')
>>>print(data)
hello,world!
DownloadCodec
Supportsdecodingarbitrarymediaasadownloadfile.Returnsatemporaryfile
thatwillbedeletedonceitgoesoutofscope.
.media_type:*/*
.format:download
Example:
>>>codec=codecs.DownloadCodec()
>>>download=codec.decode(b'abc...xyz')
>>>print(download)
>>>content=download.read()
>>>print(content)
abc...xyz
ThedownloadfilenamewillbedeterminedbyeithertheContent-Disposition
header,orbasedontherequestURLandtheContent-Typeheader.Download
collisionsareavoidedbyusingincrementingfilenameswhererequired.
Theoriginalnameusedforthedownloadfilecanbeinspectedusing.basename.
>>>download=codec.decode(b'abc...xyz',content_type='image/png',base_url='http://example.com/download/')
>>>download.name
'/var/folders/2k/qjf3np5s28zf2f58963pz2k40000gn/T/download.png'
>>>download.basename
'download.png'
Instantiation
Bydefaultthiscodecreturnsatemporaryfilethatwillbedeletedonceit
goesoutofscope.Ifyouwanttoreturntemporaryfilesthatarenot
deletedwhentheygooutofscopethenyoucaninstantiatetheDownloadCodec
withadownload_dirargument.
Forexample,todownloadfilestothecurrentworkingdirectory:
>>>importos
>>>codecs.DownloadCodec(download_dir=os.getcwd())
Decodingoptions
base_url:TheURLfromwhichthedocumentwasretrieved.Maybeusedto
generateanoutputfilenameifnoContent-Dispositionheaderexists.
content_type:TheresponseContent-Typeheader.Maybeusedtodeterminea
suffixfortheoutputfilenameifnoContent-Dispositionheaderexists.
content_disposition:TheresponseContent-Dispositionheader.Maybeusedto
indicatethedownloadfilename.
Customcodecs
CustomcodecclassesmaybecreatedbyinheritingfromBaseCodec,setting
themedia_typeandformatproperties,andimplementingoneorboth
ofthedecodeorencodemethods.
Forexample:
fromcoreapiimportcodecs
importyaml
classYAMLCodec(codecs.BaseCodec):
media_type='application/yaml'
format='yaml'
defdecode(content,**options):
returnyaml.safe_load(content)
Thecodecregistry
ToolssuchastheCoreAPIcommandlineclientrequireamethodofdiscovering
whichcodecsareinstalledonthesystem.Thisisenabledbyusingaregistry
system.
Inordertoregisteracustomcodec,thePyPIpackagemustcontainacorrectly
configuredentry_pointsoption.Typicallythisneedstobeaddedina
setup.pymodule,whichisrunwheneverpublishinganewpackageversion.
Theentry_pointsoptionmustbeadictionary,containingacoreapi.codecs
itemlistingtheavailablecodecclasses.Asanexample,thelistingforthe
codecswhichareregisteredbythecoreapipackageitselfisasfollows:
setup(
name='coreapi',
license='BSD',
...
entry_points={
'coreapi.codecs':[
'corejson=coreapi.codecs:CoreJSONCodec',
'json=coreapi.codecs:JSONCodec',
'text=coreapi.codecs:TextCodec',
'download=coreapi.codecs:DownloadCodec',
]
}
)
Externalpackages
Thefollowingthird-partypackagesareavailable.
OpenAPI
AcodecforOpenAPIschemas,alsoknownas"Swagger".InstallablefromPyPIasopenapi-codec,andavailableonGitHub.
JSONHyper-Schema
AcodecforJSONHyper-Schema.InstallablefromPyPIasjsonhyperschema-codec,andavailableonGitHub.
HAL
AcodecfortheHALhypermediaformat.InstallablefromPyPIashal-codec,andavailableonGitHub.
×Close
Search
Fromhereyoucansearchthesedocuments.Enter
yoursearchtermsbelow.