|
| 1 | +import json, falcon |
| 2 | + |
| 3 | +class ObjRequstClass: |
| 4 | + __json_content = {} |
| 5 | + |
| 6 | + def __validate_json_input(self, req): |
| 7 | + try: |
| 8 | + self.__json_content = json.loads(req.stream.read()) |
| 9 | + print 'json from client is validated! :)' |
| 10 | + return True |
| 11 | + |
| 12 | + except ValueError, e: |
| 13 | + self.__json_content = {} |
| 14 | + print 'json from client is not validted :(' |
| 15 | + return False |
| 16 | + |
| 17 | + def on_get(self, req, resp): |
| 18 | + resp.status = falcon.HTTP_200 |
| 19 | + validated = self.__validate_json_input(req) |
| 20 | + |
| 21 | + output = { |
| 22 | + 'status' : 200, |
| 23 | + 'msg' : None |
| 24 | + } |
| 25 | + |
| 26 | + if(validated == True): |
| 27 | + if 'name' in self.__json_content: |
| 28 | + output['msg'] = 'Hello {name}'.format(name=self.__json_content['name']) |
| 29 | + else: |
| 30 | + output['status'] = 404 |
| 31 | + output['msg'] = 'json input need name params' |
| 32 | + |
| 33 | + else: |
| 34 | + output['status'] = 404 |
| 35 | + output['msg'] = 'json input is not validated' |
| 36 | + |
| 37 | + resp.body = json.dumps(output) |
| 38 | + |
| 39 | + def on_post(self, req, resp): |
| 40 | + resp.status = falcon.HTTP_200 |
| 41 | + |
| 42 | + data = json.loads(req.stream.read()) |
| 43 | + |
| 44 | + equel = int(data['x']) + int(data['y']) |
| 45 | + |
| 46 | + output = { |
| 47 | + 'msg' : 'x: {x} + y: {y} is equel to {e}'.format(x=data['x'],y=data['y'],e=equel) |
| 48 | + } |
| 49 | + resp.body = json.dumps(output) |
| 50 | + |
| 51 | + def on_put(self, req, resp): |
| 52 | + resp.status = falcon.HTTP_200 |
| 53 | + output = { |
| 54 | + 'msg' : 'put is not supported for now - sorry :(' |
| 55 | + } |
| 56 | + |
| 57 | + resp.body = json.dumps(output) |
| 58 | + |
| 59 | + def on_delete(self, req, resp): |
| 60 | + resp.status = falcon.HTTP_200 |
| 61 | + output = { |
| 62 | + 'msg' : 'delete is not supported for now - sorry :(' |
| 63 | + } |
| 64 | + |
| 65 | + resp.body = json.dumps(output) |
| 66 | + |
| 67 | +api = falcon.API() |
| 68 | +api.add_route('/demo', ObjRequstClass()) |
0 commit comments