refactoring contexts, moved json writer to a class as it make more sense.

This commit is contained in:
Romain Dorgueil
2016-12-27 09:06:44 +01:00
parent f37f178630
commit 512e2ab46d
8 changed files with 173 additions and 140 deletions

View File

@ -1,18 +1,25 @@
import json
from bonobo.util.lifecycle import with_context, set_initializer, set_finalizer
from bonobo.util.lifecycle import with_context
__all__ = ['to_json', ]
__all__ = [
'from_json',
'to_json',
]
def to_json(path_or_buf):
# todo different cases + documentation
# case 1: path_or_buf is str, we consider it filename, open and write
# case 2: pob is None, json should be yielded
# case 3: pob is stream, filelike, write, gogog.
@with_context
class JsonWriter:
def __init__(self, path_or_buf):
self.path_or_buf = path_or_buf
@with_context
def _to_json(ctx, row):
def initialize(self, ctx):
assert not hasattr(ctx, 'fp'), 'One at a time, baby.'
ctx.fp = open(self.path_or_buf, 'w+')
ctx.fp.write('[\n')
ctx.first = True
def __call__(self, ctx, row):
if ctx.first:
prefix = ''
ctx.first = False
@ -20,19 +27,14 @@ def to_json(path_or_buf):
prefix = ',\n'
ctx.fp.write(prefix + json.dumps(row))
@set_initializer(_to_json)
def _to_json_initialize(ctx):
assert not hasattr(ctx, 'fp'), 'One at a time, baby.'
ctx.fp = open(path_or_buf, 'w+')
ctx.fp.write('[\n')
ctx.first = True
@set_finalizer(_to_json)
def _to_json_finalize(ctx):
def finalize(self, ctx):
ctx.fp.write('\n]')
ctx.fp.close()
del ctx.fp, ctx.first
_to_json.__name__ = 'to_json'
return _to_json
def from_json(path_or_buf):
pass
to_json = JsonWriter