93ff00b43f4c12373bc3a4726c5524e74476580b
[releng.git] / utils / test / result_collection_api / tornado_swagger_ui / example / basic.py
1 import json
2
3 import tornado.ioloop
4 from tornado.web import RequestHandler, HTTPError
5 from tornado_swagger_ui.tornado_swagger import swagger
6
7 DEFAULT_REPRESENTATION = "application/json"
8 HTTP_BAD_REQUEST = 400
9 HTTP_FORBIDDEN = 403
10 HTTP_NOT_FOUND = 404
11
12 swagger.docs()
13
14
15 @swagger.model()
16 class PropertySubclass:
17     def __init__(self, sub_property=None):
18         self.sub_property = sub_property
19
20
21 @swagger.model()
22 class Item:
23     """
24         @description:
25             This is an example of a model class that has parameters in its
26             constructor and the fields in the swagger spec are derived from
27             the parameters to __init__.
28         @notes:
29             In this case we would have property1, name as required parameters
30             and property3 as optional parameter.
31         @property property3: Item description
32         @ptype property3: L{PropertySubclass}
33         @ptype property4: C{list} of L{PropertySubclass}
34     """
35     def __init__(self,
36                  property1,
37                  property2=None,
38                  property3=None,
39                  property4=None):
40         self.property1 = property1
41         self.property2 = property2
42         self.property3 = property3
43         self.property4 = property4
44
45     def format_http(self):
46         return {
47             "property1": self.property1,
48             "property2": self.property2,
49             "property3": self.property3,
50             "property4": self.property4,
51         }
52
53     @staticmethod
54     def item_from_dict(item_dict):
55
56         if item_dict is None:
57             return None
58
59         t = Item(None)
60         t.property1 = item_dict.get('property1')
61         t.property2 = item_dict.get('property2')
62         t.property3 = item_dict.get('property3')
63         t.property4 = item_dict.get('property4')
64
65         return t
66
67     @classmethod
68     def test_classmethod(cls):
69         pass
70
71
72 items = {}
73
74
75 class GenericApiHandler(RequestHandler):
76     """
77     The purpose of this class is to take benefit of inheritance and prepare
78     a set of common functions for
79     the handlers
80     """
81
82     def initialize(self):
83         """ Prepares the database for the entire class """
84         pass
85
86     def prepare(self):
87         if self.request.method != "GET" and self.request.method != "DELETE":
88             self.json_args = None
89             content_type = self.request.headers.get("Content-Type")
90             if content_type is not None:
91                 if content_type.startswith(DEFAULT_REPRESENTATION):
92                     try:
93                         self.json_args = json.loads(self.request.body)
94                     except (ValueError, KeyError, TypeError) as error:
95                         raise HTTPError(HTTP_BAD_REQUEST,
96                                         "Bad Json format [{}]".
97                                         format(error))
98
99     def finish_request(self, json_object):
100         self.write(json.dumps(json_object))
101         self.set_header("Content-Type", DEFAULT_REPRESENTATION)
102         self.finish()
103
104
105 class ItemNoParamHandler(GenericApiHandler):
106     @swagger.operation(nickname='create')
107     def post(self):
108         """
109             @param body: create a item.
110             @type body: L{Item}
111             @in body: body
112             @return 200: item is created.
113             @raise 400: invalid input
114         """
115         property1 = self.json_args.get('property1')
116         item = Item.item_from_dict(self.json_args)
117         items[property1] = item
118         Item.test_classmethod()
119         self.finish_request(item.format_http())
120
121     @swagger.operation(nickname='list')
122     def get(self):
123         """
124            @rtype: L{Item}
125         """
126         res = []
127         for key, value in items.iteritems():
128             res.append(value.format_http())
129         self.finish_request(res)
130
131     def options(self):
132         """
133         I'm not visible in the swagger docs
134         """
135         self.finish_request("I'm invisible in the swagger docs")
136
137
138 class ItemHandler(GenericApiHandler):
139     @swagger.operation(nickname='get')
140     def get(self, arg):
141         """
142             @rtype: L{Item}
143             @description: get information of a item
144             @notes:
145                 get a item,
146
147                 This will be added to the Implementation Notes.
148                 It lets you put very long text in your api.
149         """
150         self.finish_request(items[arg].format_http())
151
152     @swagger.operation(nickname='delete')
153     def delete(self, arg):
154         """
155             @description: delete a item
156             @notes:
157                 delete a item in items
158         """
159         del items[arg]
160         self.finish_request("success")
161
162
163 class ItemOptionParamHandler(GenericApiHandler):
164     @swagger.operation(nickname='create')
165     def post(self, arg1, arg2=''):
166         """
167         @return 200: case is created
168         """
169         fs = open("/home/%s/%s" % (arg1, arg2), "wb")
170         fs.write(self.request.body)
171         self.write("success")
172
173
174 class ItemQueryHandler(GenericApiHandler):
175     @swagger.operation(nickname='query')
176     def get(self):
177         """
178            @param property1:
179            @type property1: L{string}
180            @in property1: query
181            @required property1: False
182
183            @param property2:
184            @type property2: L{string}
185            @in property2: query
186            @required property2: True
187            @rtype: L{Item}
188            @notes: GET /item?property1=1&property2=1
189         """
190         property1 = self.get_query_argument("property1", None)
191         property2 = self.get_query_argument("property2", None)
192
193         res = []
194         if property1 is None:
195             for key, value in items.iteritems():
196                 if property2 is None:
197                     res.append(value.format_http())
198                 elif value.property2 == property2:
199                     res.append(value.format_http())
200         elif property1 in items:
201             if items.get(property1).property2 == property2:
202                 res.append(items.get(property1).format_http())
203
204         self.finish_request(res)
205
206
207 def make_app():
208     return swagger.Application([
209         (r"/item", ItemQueryHandler),
210         (r"/items", ItemNoParamHandler),
211         (r"/items/([^/]+)", ItemHandler),
212         (r"/items/([^/]+)/cases/([^/]+)", ItemOptionParamHandler),
213     ])
214
215
216 if __name__ == "__main__":
217     app = make_app()
218     app.listen(711)
219     tornado.ioloop.IOLoop.current().start()