Package couchdbkit :: Module external
[hide private]
[frames] | no frames]

Source Code for Module couchdbkit.external

 1  # -*- coding: utf-8 - 
 2  # 
 3  # This file is part of couchdbkit released under the MIT license.  
 4  # See the NOTICE for more information. 
 5   
 6  import sys 
 7   
 8  from .utils import json 
 9   
10 -class External(object):
11 """ simple class to handle an external 12 ans send the response. 13 14 example: 15 16 from couchdbkit.external import External 17 from couchdbkit.utils import json 18 19 class Test(External): 20 21 def handle_line(self, line): 22 self.send_response(200, 23 "got message external object %s" % json.dumps(line), 24 {"Content-type": "text/plain"}) 25 26 if __name__ == "__main__": 27 Test().run() 28 29 """ 30
31 - def __init__(self, stdin=sys.stdin, stdout=sys.stdout):
32 self.stdin = stdin 33 self.stdout = stdout
34
35 - def handle_line(self, line):
36 raise NotImplementedError
37
38 - def write(self, line):
39 self.stdout.write("%s\n" % line) 40 self.stdout.flush()
41
42 - def lines(self):
43 line = self.stdin.readline() 44 while line: 45 yield json.loads(line) 46 line = self.stdin.readline()
47
48 - def run(self):
49 for line in self.lines(): 50 self.handle_line(line)
51
52 - def send_response(self, code=200, body="", headers={}):
53 resp = { 54 'code': code, 55 'body': body, 56 'headers': headers 57 } 58 self.write(json.dumps(resp))
59