File: tutorial3-netstring-reversal.py

package info (click to toggle)
python-parsley 1.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,048 kB
  • sloc: python: 9,897; makefile: 127
file content (83 lines) | stat: -rw-r--r-- 2,143 bytes parent folder | download | duplicates (4)
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
from twisted.internet.defer import Deferred
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet.protocol import Factory
from twisted.internet.task import react

from parsley import makeProtocol, stack


grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)

netstring = digits:length ':' <anything{length}>:string ',' -> string

receiveNetstring = netstring:string -> receiver.netstringReceived(string)
"""


class NetstringReversalWrapper(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def sendNetstring(self, string):
        self.wrapped.sendNetstring(string[::-1])


class NetstringSender(object):
    def __init__(self, transport):
        self.transport = transport

    def sendNetstring(self, string):
        self.transport.write('%d:%s,' % (len(string), string))


class NetstringSplittingWrapper(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def netstringReceived(self, string):
        splitpoint = len(string) // 2
        self.wrapped.netstringFirstHalfReceived(string[:splitpoint])
        self.wrapped.netstringSecondHalfReceived(string[splitpoint:])

    def __getattr__(self, attr):
        return getattr(self.wrapped, attr)


class SplitNetstringReceiver(object):
    currentRule = 'receiveNetstring'

    def __init__(self, sender):
        self.sender = sender

    def prepareParsing(self, parser):
        pass

    def finishParsing(self, reason):
        pass

    def netstringFirstHalfReceived(self, string):
        self.sender.sendNetstring(string)

    def netstringSecondHalfReceived(self, string):
        pass

pass  # begin protocol definition
NetstringProtocol = makeProtocol(
    grammar,
    stack(NetstringReversalWrapper, NetstringSender),
    stack(NetstringSplittingWrapper, SplitNetstringReceiver))

class NetstringFactory(Factory):
    protocol = NetstringProtocol


def main(reactor):
    server = TCP4ServerEndpoint(reactor, 1234)
    d = server.listen(NetstringFactory())
    d.addCallback(lambda p: Deferred())  # listen forever
    return d


react(main, [])