Debian Codegraph @

examples/example_app.py

raw symbols SCIP
1 """
2 A general example
3 """
4 from flask import Flask, jsonify, request
5 from flask.views import MethodView
6
7 from flasgger import Swagger
8 from flasgger.utils import swag_from
9
10
11 app = Flask(__name__)
12
13
14 # config your API specs
15 # you can define multiple specs in the case your api has multiple versions
16 # ommit configs to get the default (all views exposed in /spec url)
17 # rule_filter is a callable that receives "Rule" object and
18 # returns a boolean to filter in only desired views
19
20 app.config['SWAGGER'] = {
21 "swagger_version": "2.0",
22 "title": "Flasgger",
23 "headers": [
24 ('Access-Control-Allow-Origin', '*'),
25 ('Access-Control-Allow-Methods', "GET, POST, PUT, DELETE, OPTIONS"),
26 ('Access-Control-Allow-Credentials', "true"),
27 ],
28 "specs": [
29 {
30 "version": "0.0.1",
31 "title": "Api v1",
32 "endpoint": 'v1_spec',
33 "description": 'This is the version 1 of our API',
34 "route": '/v1/spec',
35 # rule_filter is optional
36 # it is a callable to filter the views to extract
37 "rule_filter": lambda rule: rule.endpoint.startswith(
38 'should_be_v1_only'
39 ),
40 # definition_filter is optional
41 # it is a callable to filter the definition models to include
42 "definition_filter": lambda definition: (
43 'v1_model' in definition.tags)
44 },
45 {
46 "version": "0.0.2",
47 "title": "Api v2",
48 "description": 'This is the version 2 of our API',
49 "endpoint": 'v2_spec',
50 "route": '/v2/spec',
51 "rule_filter": lambda rule: rule.endpoint.startswith(
52 'should_be_v2_only'
53 ),
54 "definition_filter": lambda definition: (
55 'v2_model' in definition.tags)
56 }
57 ]
58 }
59
60 swag = Swagger(app) # you can pass config here Swagger(config={})
61
62
63 @app.after_request
64 def allow_origin(response):
65 response.headers['Access-Control-Allow-Origin'] = 'http://example.com'
66 response.headers['Access-Control-Allow-Credentials'] = 'true'
67
68 return response
69
70
71 class UserAPI(MethodView):
72
73 def get(self, team_id):
74 """
75 Get a list of users
76 First line is the summary
77 All following lines until the hyphens is added to description
78 ---
79 tags:
80 - users
81 parameters:
82 - name: team_id
83 in: path
84 description: ID of team (type any number)
85 required: true
86 type: integer
87 default: 42
88 responses:
89 200:
90 description: Returns a list of users
91 schema:
92 type: array
93 items:
94 $ref: '#/definitions/User'
95 """
96 data = {
97 "users": [
98 {"name": "Steven Wilson", "team": team_id},
99 {"name": "Mikael Akerfeldt", "team": team_id},
100 {"name": "Daniel Gildenlow", "team": team_id}
101 ]
102 }
103 return jsonify(data)
104
105 def post(self):
106 """
107 Create a new user
108 First line is the summary
109 All following lines until the hyphens is added to description
110 ---
111 tags:
112 - users
113 parameters:
114 - in: body
115 name: body
116 schema:
117 id: User
118 required:
119 - team
120 - name
121 properties:
122 team:
123 type: integer
124 description: team for user
125 default: 42
126 name:
127 type: string
128 description: name for user
129 default: Russel Allen
130 responses:
131 201:
132 description: New user created
133 schema:
134 type: array
135 items:
136 $ref: '#/definitions/User'
137 import: "not_found.yaml"
138 """
139 return jsonify(
140 {"data": request.json, "status": "New user created"}
141 ), 201
142
143
144 view = UserAPI.as_view('users')
145 app.add_url_rule(
146 '/v1/users/<int:team_id>',
147 view_func=view,
148 methods=['GET'],
149 endpoint='should_be_v1_only'
150 )
151 app.add_url_rule(
152 '/v1/users',
153 view_func=view,
154 methods=['POST'],
155 endpoint='should_be_v1_only_post'
156 )
157
158 # LOADING SPECS FROM EXTERNAL FILE
159
160
161 @app.route('/v1/decorated/<username>', endpoint='should_be_v1_only_username')
162 @swag_from('username_specs.yml')
163 def fromfile_decorated(username):
164 return jsonify({'username': username})
165
166 @app.route('/v1/decorated_no_descr/<username>', endpoint='should_be_v1_only_username_no_descr')
167 @swag_from('username_specs_no_descr.yml')
168 def fromfile_decorated_no_descr(username):
169 return jsonify({'username': username})
170
171 @app.route('/v1/decorated_no_sep/<username>', endpoint='should_be_v1_only_username_no_sep')
172 @swag_from('username_specs_no_sep.yml')
173 def fromfile_decorated_no_sep(username):
174 return jsonify({'username': username})
175
176 @app.route('/v1/decorated_bom/<username>', endpoint='should_be_v1_only_username_bom')
177 @swag_from('username_specs_bom.yml')
178 def fromfile_decorated_bom(username):
179 return jsonify({'username': username})
180
181 @app.route('/v1/decorated_utf16/<username>', endpoint='should_be_v1_only_username_utf16')
182 @swag_from('username_specs_utf16.yml')
183 def fromfile_decorated_utf16(username):
184 return jsonify({'username': username})
185
186 @app.route('/v1/decorated_utf32/<username>', endpoint='should_be_v1_only_username_utf32')
187 @swag_from('username_specs_utf32.yml')
188 def fromfile_decorated_utf32(username):
189 return jsonify({'username': username})
190
191
192 try:
193 from pathlib import Path
194 @app.route('/v1/decorated_pathlib_path/<username>',
195 endpoint='should_be_v1_only_username_pathlib_path')
196 @swag_from(Path('username_specs.yml'))
197 def fromfile_decorated(username):
198 return jsonify({'username': username})
199 except ImportError:
200 pass
201
202 # OR
203
204
205 @app.route('/v1/fileindoc/<username>', endpoint='should_be_v1_only_username_1')
206 def fromfile_indocstring(username):
207 """
208 file: username_specs.yml
209 """
210 return jsonify({'username': username})
211
212 @app.route('/v1/fileindoc_no_descr/<username>', endpoint='should_be_v1_only_username_no_descr_1')
213 def fromfile_indocstring_no_descr(username):
214 """
215 file: username_specs_no_descr.yml
216 """
217 return jsonify({'username': username})
218
219 @app.route('/v1/fileindoc_no_sep/<username>', endpoint='should_be_v1_only_username_no_sep_1')
220 def fromfile_indocstring_no_sep(username):
221 """
222 file: username_specs_no_sep.yml
223 """
224 return jsonify({'username': username})
225
226
227 # DEFINITIONS FROM OBJECTS
228
229 @swag.definition('Hack', tags=['v2_model'])
230 def hack(subitems):
231 """
232 Hack Object
233 ---
234 properties:
235 hack:
236 type: string
237 description: it's a hack
238 subitems:
239 type: array
240 items:
241 $ref: '#/definitions/SubItem'
242 """
243 return {
244 'hack': "string",
245 'subitems': [subitem.dump() for subitem in subitems]
246 }
247
248
249 @swag.definition('SubItem', tags=['v2_model'])
250 class SubItem(object):
251 """
252 SubItem Object
253 ---
254 properties:
255 bla:
256 type: string
257 description: Bla
258 blu:
259 type: integer
260 description: Blu
261 """
262 def __init__(self, bla, blu):
263 self.bla = str(bla)
264 self.blu = int(blu)
265
266 def dump(self):
267 return dict(vars(self).items())
268
269
270 @app.route("/v2/resource", endpoint="should_be_v2_only")
271 def bla():
272 """
273 An endpoint that isn't using method view
274 ---
275 tags:
276 - hacking
277 responses:
278 200:
279 description: Hacked some hacks
280 schema:
281 $ref: '#/definitions/Hack'
282 """
283 subitems = [SubItem("string", 0)]
284 return jsonify(hack(subitems))
285
286
287 @swag.definition('rec_query_context', tags=['v2_model'])
288 class RecQueryContext(object):
289 """
290 Recommendation Query Context
291 ---
292 required:
293 - origin
294 properties:
295 origin:
296 type: string
297 default: sugestao
298 last_event:
299 type: object
300 schema:
301 $ref: '#/definitions/rec_query_context_last_event'
302 """
303 def __init__(self, origin, last_event=None):
304 self.origin = origin
305 self.last_event = last_event
306
307 def dump(self):
308 data = {'origin': self.origin}
309 if self.last_event:
310 data.update({'last_event': self.last_event.dump()})
311 return data
312
313
314 @swag.definition('rec_query_context_last_event', tags=['v2_model'])
315 class RecQueryContextLastEvent(object):
316 """
317 RecQueryContext Last Event Definition
318 ---
319 properties:
320 event:
321 type: string
322 default: apply
323 data:
324 type: object
325 schema:
326 $ref: '#/definitions/rec_query_context_last_event_data'
327 """
328 def __init__(self, event=None, data=None):
329 self.event = event
330 self.data = data
331
332 def dump(self):
333 data = {}
334 if self.event:
335 data.update({'event': self.event})
336 if self.data:
337 data.update({'data': self.data.dump()})
338 return data
339
340
341 @swag.definition('rec_query_context_last_event_data', tags=['v2_model'])
342 class RecQueryContextLastEventData(object):
343 """
344 RecQueryContextLastEvent Data Object
345 ---
346 properties:
347 candidate_id:
348 type: integer
349 default: 123456
350 opening_id:
351 type: integer
352 default: 324345435
353 company_id:
354 type: integer
355 default: 324345435
356 datetime:
357 type: string
358 format: date-time
359 default: 2014-09-10T11:41:00.12343-03:00
360 recruiter_id:
361 type: integer
362 default: 435345
363 context:
364 $ref: '#/definitions/rec_query_context'
365 """
366 def __init__(self, candidate_id=None, opening_id=None, company_id=None,
367 datetime=None, recruiter_id=None):
368 self.candidate_id = candidate_id
369 self.opening_id = opening_id
370 self.company_id = company_id
371 self.datetime = datetime
372 self.recruiter_id = recruiter_id
373
374 def dump(self):
375 data = {}
376 for var in ['candidate_id', 'opening_id', 'company_id', 'datetime',
377 'recruiter_id']:
378 if var in vars(self):
379 data.update({var: vars(self)[var]})
380 return data
381
382
383 @app.route("/v2/recommendation/<target_type>/<item_type>", methods=['POST'],
384 endpoint="should_be_v2_only_recommendation")
385 def recommend(target_type, item_type):
386 """
387 Recommendation
388 Get a single item_type as recommendation for the target_type
389 ---
390 tags:
391 - recommendation
392 parameters:
393 - name: target_type
394 in: path
395 description: currently only "candidate" is supported
396 required: true
397 type: string
398 default: candidate
399 - name: item_type
400 in: path
401 description: currently only "openings" is supported
402 required: true
403 type: string
404 default: openings
405 - in: body
406 name: body
407 schema:
408 id: rec_query
409 required:
410 - candidate_id
411 - context
412 properties:
413 candidate_id:
414 type: integer
415 description: Id of the target (candidate / user)
416 default: 123456
417 exclude:
418 type: array
419 description: item_ids to exclude from recs
420 default: [12345, 123456]
421 items:
422 type: integer
423 context:
424 type: object
425 schema:
426 $ref: '#/definitions/rec_query_context'
427 responses:
428 200:
429 description: A single recommendation item
430 schema:
431 id: rec_response
432 properties:
433 opening_id:
434 type: integer
435 description: The id of the opening
436 default: 123456
437 204:
438 description: No recommendation found
439 """
440
441 data = {
442 "opening_id": 12312313434
443 }
444 return jsonify(data)
445
446
447 @app.route("/")
448 def hello():
449 return """
450 <h1> Welcome to Flasgger demo application</h1>
451 This app exposes two API versions
452 <ul>
453 <li><a href="/apidocs/index.html?url=/v1/spec">Api Version 1</a></li>
454 <li><a href="/apidocs/index.html?url=/v2/spec">Api Version 2</a></li>
455 </ul>
456 <p>
457 As you can see the APIs is served by the same swagger UI on
458 <a href="/apidocs/index.html">Api docs</a>
459 </p>
460 <p>
461 Flasgger <a href="https://github.com/rochacbruno/flasgger">
462 https://github.com/rochacbruno/flasgger</a>
463 </p>
464 """
465
466 if __name__ == "__main__":
467 app.run(debug=True)