bundle2: introduce a `addparam` method on part

We make it easier to add new parameters after the part creation. As for the
``data`` attribute we make sure the part generation has not begun yet.
This commit is contained in:
Pierre-Yves David 2014-05-22 11:38:40 -07:00
parent 3c42f04f04
commit 76215be0d0
2 changed files with 32 additions and 8 deletions

View File

@ -556,8 +556,13 @@ class bundlepart(object):
handler.
The part payload is contained in ``part.data``. It could be raw bytes or a
generator of byte chunks. The data attribute cannot be modified after the
generation has begun.
generator of byte chunks.
You can add parameters to the part using the ``addparam`` method.
Parameters can be either mandatory (default) or advisory. Remote side
should be able to safely ignore the advisory ones.
Both data and parameters cannot be modified after the generation has begun.
"""
def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
@ -565,8 +570,8 @@ class bundlepart(object):
self.id = None
self.type = parttype
self._data = data
self.mandatoryparams = mandatoryparams
self.advisoryparams = advisoryparams
self._mandatoryparams = list(mandatoryparams)
self._advisoryparams = list(advisoryparams)
# status of the part's generation:
# - None: not started,
# - False: currently generated,
@ -582,6 +587,24 @@ class bundlepart(object):
return self._data
data = property(__getdata, __setdata)
@property
def mandatoryparams(self):
# make it an immutable tuple to force people through ``addparam``
return tuple(self._mandatoryparams)
@property
def advisoryparams(self):
# make it an immutable tuple to force people through ``addparam``
return tuple(self._advisoryparams)
def addparam(self, name, value='', mandatory=True):
if self._generated is not None:
raise ReadOnlyPartError('part is being generated')
params = self._advisoryparams
if mandatory:
params = self._mandatoryparams
params.append((name, value))
# methods used to generates the bundle2 stream
def getchunks(self):
if self._generated is not None:

View File

@ -106,10 +106,11 @@ Create an extension to test bundle2 API
> bundler.newpart('test:empty')
> bundler.newpart('test:song', data=ELEPHANTSSONG)
> bundler.newpart('test:debugreply')
> bundler.newpart('test:math',
> [('pi', '3.14'), ('e', '2.72')],
> [('cooking', 'raw')],
> '42')
> mathpart = bundler.newpart('test:math')
> mathpart.addparam('pi', '3.14')
> mathpart.addparam('e', '2.72')
> mathpart.addparam('cooking', 'raw', mandatory=False)
> mathpart.data = '42'
> if opts['unknown']:
> bundler.newpart('test:UNKNOWN', data='some random content')
> if opts['parts']: