Source

callchain / callchain / chainlet / io.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# -*- coding: utf-8 -*-
'''callchain dumpers'''

import csv
import codecs
import marshal
from operator import setitem
from cgi import parse_multipart

from appspace import appifies
from stuf.utils import exhaustmap

from callchain import ResetLocalMixin

from callchain.chainlet import imps
from callchain.chainlet.base import Chainlet
from callchain.chainlet.keys import KDumps, KLoads, KIO


class _Package(ResetLocalMixin):

    '''data package'''

    def __init__(self, data, mime, charset=None):
        super(_Package, self).__init__()
        self.data = data
        self.mime = mime
        self.charset = charset


class iolet(Chainlet):

    '''input/output mixin'''

    def _process(self, encoder, mime, charset=None):
        with self._context():
            self._xtend(self._map(
                lambda x: _Package(encoder(x), mime, charset), self._iterable,
            ))
        return self


@appifies(KIO)
class filet(Chainlet):

    '''file input/output chainlet'''

    def read(self, mode='rb', encoding=None, errors='strict', *paths):
        '''
        read incoming things from files

        @param mode: mode to open files (default: 'r')
        @param encoding: encoding for text data (default: `None`)
        @param errors: error handling in encoding text data (default: 'strict')
        @param *paths: sequence of filesystem paths
        '''
        with self._context:
            append = self._append
            for path in paths:
                with codecs.open(path, mode, encoding) as f:
                    append(f.read())
        return self

    def write(self, mode='rb', encoding=None, errors='strict', *paths):
        '''
        write outgoing things to files

        @param mode: mode to open files (default: 'r')
        @param encoding: encoding for text data (default: `None`)
        @param errors: error handling in encoding text data (default: 'strict')
        @param *paths: sequence of filesystem paths
        '''
        values = self.value()
        for idx, path in enumerate(paths):
            with codecs.open(path, mode, encoding) as f:
                f.write(values[idx])
        return self


@appifies(KDumps)
class Dumps(iolet):

    '''dumper'''

    def bencode(self):
        '''
        bencode dumper

        http://en.wikipedia.org/wiki/Bencode
        http://pypi.python.org/pypi/bencode/
        '''
        try:
            return self._process(imps.bencode, 'application/x-bittorrent')
        except AttributeError:
            raise ImportError('requires "bencode" library')

    def bson(self):
        '''
        binary JSON dumper

        http://en.wikipedia.org/wiki/BSON
        http://pypi.python.org/pypi/bson/
        '''
        try:
            return self._process(imps.bson.dumps, 'application/x-bson')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires "bson" library')

    def csv(self, **kw):
        '''comma-separated values dumper'''
        def dumps(data, **kw):
            dumped = imps.StringIO()
            csvw = csv.writer(dumped, **kw)
            for row in data:
                csvw.writerow(row)
            return dumped.getvalue()
        return self._process(lambda x: dumps(x, **kw), 'text/csv')

    def excel(self, **kw):
        '''
        M$ excel dumper

        http://pypi.python.org/pypi/xlrd/
        http://pypi.python.org/pypi/xlwt/
        '''
        try:
            workbook = imps.xlwt.Workbook  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires the "xlrd" and "xlwt" libraries')
        def dumps(data, **kw): #@IgnorePep8
            wb = workbook(encoding='utf8', **kw)
            ws = wb.add_sheet(kw.get('title', 'Worksheet 1'))
            write = ws.write
            for i, row in enumerate(data):
                for j, col in enumerate(row):
                    write(i, j, col)
            stream = imps.StringIO()
            wb.save(stream)
            return stream.getvalue()
        return self._process(
            self._partial(dumps, **kw), 'application/vnd.ms-excel',
        )

    def html(self, **kw):
        '''
        html dumper

        http://pypi.python.org/pypi/lxml/
        '''
        try:
            return self._process(
                lambda x: imps.html.tostring(x, **kw), 'text/html',  # @UndefinedVariable @IgnorePep8
            )
        except AttributeError:
            raise ImportError('requires "lxml" library')

    def json(self, **kw):
        '''JavaScript Object Notation (JSON) dumper'''
        return self._process(
            lambda x: imps.json.dumps(x, use_decimal=True, **kw),
            'application/json',
        )

    def jsonpickle(self):
        '''JavaScript Object Notation (JSON) pickle dumper'''
        try:
            return self._process(imps.jsonpickle.encode, 'application/json')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires the "jsonpickle" library')

    def marshal(self):
        '''
        python marshal talker (not guaranteed to interoperate between major
        Python releases)

        ACCEPTING ARBITRARY MARSHAL DATA MAY BE UNSAFE!!!
        '''
        return self._process(marshal.dumps, 'application/x-python-marshal')

    def message_pack(self):
        '''
        message pack dumper

        http://msgpack.org/
        http://wiki.msgpack.org/display/MSGPACK/QuickStart+for+Python

        http://pypi.python.org/pypi/msgpack-python/
        '''
        try:
            return self._process(imps.msgpack.packb, 'application/x-msgpack')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires "msgpack" library')

    def multipart(self):
        '''form multipart dumper'''
        try:
            return self._process(
                lambda x: imps.encode_multipart_formdata(
                    x, boundary='----------AaB03x',
                ),
                'multipart/form-data; boundary=----------AaB03x',
            )
        except AttributeError:
            raise ImportError('requires "requests" or "urllib3" packages')

    def netstring(self):
        '''
        netstring dumper

        http://cr.yp.to/proto/netstrings.txt

        http://pypi.python.org/pypi/netstring
        '''
        try:
            return self._process(
                imps.netstring.encode, 'application/x-netstring',   # @UndefinedVariable @IgnorePep8
            )
        except AttributeError:
            raise ImportError('requires "netstring" library')

    def pickle(self):
        '''
        python pickle talker (not guaranteed to interoperate between major
        Python releases. ACCEPTING ARBITRARY PICKLE DATA MAY BE UNSAFE!!!
        '''
        pickle = imps.pickle  # @UndefinedVariable
        return self._process(
            lambda x: pickle.dumps(x, protocol=pickle.HIGHEST_PROTOCOL), 
            'application/python-pickle',
        )

    def plist(self):
        '''property list dumper'''
        return self._process(imps.plist_dumps, 'application/x-plist')

    def protobuf(self):
        '''
        google protocol buffers dumper

        http://code.google.com/p/protobuf/

        http://pypi.python.org/pypi/protobuf/
        '''
        return self._process(
            lambda x: x.SerializeToString(), 'application/x-protobuf',
        )

    def thrift(self):
        '''
        thrift dumper
    
        http://thrift.apache.org/
    
        http://pypi.python.org/pypi/thrift/
        '''
        try:
            return self._process(imps.thrift.serialize, 'application/x-thrift')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires "thrift" library')

    def tnetstring(self):
        '''
        tnetstring loader
    
        http://pypi.python.org/pypi/tnetstring/
        '''
        try:
            return self._process(
                imps.tnetstring.dumps, 'application/x-tnetstring',  # @UndefinedVariable @IgnorePep8
            )
        except AttributeError:
            raise ImportError('requires "tnetstring" library')

    def urlencode(self, **kw):
        '''urlencode dumper'''
        return self._process(
            lambda x: imps.urlencode(x, **kw),  # @UndefinedVariable @IgnorePep8
            'application/x-www-form-urlencoded',
        )

    def xml(self, **kw):
        '''
        extensible markup language loader

        http://pypi.python.org/pypi/lxml/
        '''
        return self._process(
            lambda x: imps.etree.tostring(x, **kw), 'text/xml',
        )

    def xmlrpc(self, **kw):
        '''
        extensible markup language remote procedure call dumper
        '''
        return self._process(
            lambda x: imps.xmlrpc.dumps(x, **kw), 'text/xml',   # @UndefinedVariable @IgnorePep8
        )

    def yaml(self, **kw):
        '''
        YAML ain't markup language dumper

        http://en.wikipedia.org/wiki/YAML

        http://pypi.python.org/pypi/PyYAML/
        '''
        try:
            return self._process(
                lambda x: imps.yaml.dump(x, **kw), 'application/x-yaml',  # @UndefinedVariable @IgnorePep8
            )
        except AttributeError:
            raise ImportError('requires PyYaml module')


@appifies(KLoads)
class Loads(iolet):

    '''loader'''

    def bencode(self):
        '''
        bencode dumper

        http://en.wikipedia.org/wiki/Bencode
        http://pypi.python.org/pypi/bencode/
        '''
        try:
            return self._process(imps.bdecode, 'application/x-bittorrent')
        except AttributeError:
            raise ImportError('requires "bencode" library')

    def bson(self):
        '''
        binary JSON loader

        http://en.wikipedia.org/wiki/BSON
        http://pypi.python.org/pypi/bson/
        '''
        try:
            return self._process(imps.bson.loads, 'application/x-bson')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires "bson" library')

    def csv(self, **kw):
        '''comma-separated values loader'''
        def loads(data, **kw):
            return list(r for r in csv.reader(imps.StringIO(data), **kw))
        return self._process(lambda x: loads(x, **kw), 'text/csv')

    def excel(self, **kw):
        '''
        M$ excel serialization

        http://pypi.python.org/pypi/xlrd/
        http://pypi.python.org/pypi/xlwt/
        '''
        try:
            workbook = imps.xlrd.open_workbook  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires the "xlrd" and "xlwt" libraries')
        def loads(data, **kw): #@IgnorePep8
            wb = workbook(file_contents=data, **kw)
            new_workbook = list()
            oappend = new_workbook.append
            for sheet in wb.sheets():
                cellvalue = sheet.cell_value
                new_sheet = list()
                nappend = new_sheet.append
                for row in range(sheet.nrows):
                    new_row = list()
                    iappend = new_row.append
                    for col in xrange(sheet.ncols):
                        iappend(cellvalue(row, col))
                    nappend(new_row)
                oappend(new_sheet)
            return new_workbook
        return self._process(
            lambda x: loads(x, **kw), 'application/vnd.ms-excel',
        )

    def html(self, **kw):
        '''
        html serialization

        http://pypi.python.org/pypi/lxml/
        '''
        return self._process(
            lambda x: imps.html.fromstring(x, **kw), 'text/html',  # @UndefinedVariable @IgnorePep8
        )

    def json(self, **kw):
        '''JavaScript Object Notation (JSON) serialization'''
        return self._process(
            lambda x: imps.json.loads(x, use_decimal=True, **kw),
            'application/json',
        )

    def jsonpickle(self):
        '''JavaScript Object Notation (JSON) pickle serialization'''
        try:
            return self._process(imps.jsonpickle.decode, 'application/json')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires the "jsonpickle" library')

    def marshal(self):
        '''
        python marshal talker (not guaranteed to interoperate between major
        Python releases)

        ACCEPTING ARBITRARY MARSHAL DATA MAY BE UNSAFE!!!
        '''
        return self._process(marshal.loads, 'application/x-python-marshal')

    def message_pack(self):
        '''
        message pack serialization key

        http://msgpack.org/
        http://wiki.msgpack.org/display/MSGPACK/QuickStart+for+Python

        http://pypi.python.org/pypi/msgpack-python/
        '''
        try:
            return self._process(imps.msgpack.unpackb, 'application/x-msgpack')  # @UndefinedVariable @IgnorePep8
        except AttributeError:
            raise ImportError('requires "msgpack" library')

    def multipart(self):
        '''form multipart serialization'''
        def loads(data):
            q = parse_multipart(
                imps.StringIO(data), dict(boundary='----------AaB03x')
            )
            exhaustmap(
                q, lambda x, y: setitem(q, x, y[0]), lambda x: len(x[1]) == 1
            )
            return q
        return self._process(
            loads, 'multipart/form-data; boundary=----------AaB03x',
        )

    def netstring(self):
        '''
        netstring serialization key

        http://cr.yp.to/proto/netstrings.txt

        http://pypi.python.org/pypi/netstring
        '''
        try:
            return self._process(
                lambda x: imps.netstring.decode(x)[0],  # @UndefinedVariable @IgnorePep8
                'application/x-netstring',
            )
        except AttributeError:
            raise ImportError('requires "netstring" library')

    def pickle(self):
        '''
        python pickle talker (not guaranteed to interoperate between major
        Python releases. ACCEPTING ARBITRARY PICKLE DATA MAY BE UNSAFE!!!
        '''
        return self._process(imps.pickle.loads, 'application/x-python-pickle')  # @UndefinedVariable @IgnorePep8

    def plist(self):
        '''property list serialization key'''
        return self._process(imps.plist_loads, 'application/x-plist')

    def protobuf(self, **kw):
        '''
        google protocol buffers serialization

        http://code.google.com/p/protobuf/

        http://pypi.python.org/pypi/protobuf/
        '''
        proto = kw.get('proto')
        def load(data): #@IgnorePep8
            p = proto()
            p.ParseFromString(data)
            return p
        return self._process(load, 'application/x-protobuf')

    def thrift(self, base):
        '''
        thrift serialization key
    
        http://thrift.apache.org/
    
        http://pypi.python.org/pypi/thrift/
        '''
        try:
            return self._process(
               lambda x: imps.thrift.deserialize(x, base),  # @UndefinedVariable @IgnorePep8
               'application/x-thrift',
            )
        except AttributeError:
            raise ImportError('requires "thrift" library')

    def tnetstring(self):
        '''
        tnetstring loader
    
        http://pypi.python.org/pypi/tnetstring/
        '''
        try:
            return self._process(
                imps.tnetstring.loads, 'application/x-tnetstring',  # @UndefinedVariable @IgnorePep8
            )
        except AttributeError:
            raise ImportError('requires "tnetstring" library')

    def urlencode(self, **kw):
        '''urlencode loader'''
        def loads(data, **kw):
            q = imps.parse_qs(data, **kw)
            exhaustmap(
                q, lambda x, y: setitem(q, x, y[0]), lambda x: len(x[1]) == 1,
            )
            return q
        return self._process(lambda x: loads(x, **kw))

    def xml(self, **kw):
        '''
        extensible markup language loader

        http://pypi.python.org/pypi/lxml/
        '''
        return self._process(
            lambda x: imps.etree.fromstring(x, **kw), 'text/xml', 'utf-8',
        )

    def xmlrpc(self, **kw):
        '''
        extensible markup language remote procedure call serialization key
        '''
        return self._process(
            lambda x: imps.xmlrpc.loads(x, type, **kw)[0], 'text/xml',  # @UndefinedVariable @IgnorePep8
        )

    def yaml(self, **kw):
        '''
        YAML ain't markup language dumper

        http://en.wikipedia.org/wiki/YAML

        http://pypi.python.org/pypi/PyYAML/
        '''
        try:
            return self._process(
                lambda x: imps.yaml.load(x, **kw), 'application/x-yaml',  # @UndefinedVariable @IgnorePep8
            )
        except AttributeError:
            raise ImportError('requires PyYaml module')