Debian Codegraph @

examples/lazy_string.py

raw symbols SCIP
1 """
2 Test the use of LazyString to populate a template at runtime.
3 """
4
5 from flask import Flask, jsonify, request
6
7 from flasgger import Swagger, LazyString, LazyJSONEncoder
8
9
10 class CustomFlaskAppWithEncoder(Flask):
11 json_provider_class = LazyJSONEncoder
12
13
14 app = CustomFlaskAppWithEncoder(__name__)
15 app.testing = True
16
17 # Set the LAzyString JSON Encoder
18 """
19 DeprecationWarning: 'app.json_encoder' is deprecated
20 and will be removed in Flask 2.3. Customize 'app.json_provider_class' or 'app.json' instead.
21 """
22 app.json_encoder = LazyJSONEncoder # flask < 2.3
23
24 app.config['SWAGGER'] = {
25 'uiversion': 2
26 }
27
28 template = dict(
29 info={
30 'title': LazyString(lambda: 'Lazy Title'),
31 'version': LazyString(lambda: '99.9.9'),
32 'description': LazyString(lambda: 'Hello Lazy World'),
33 'termsOfService': LazyString(lambda: '/there_is_no_tos')
34 },
35 host=LazyString(lambda: request.host),
36 schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')],
37 foo=LazyString(lambda: "Bar")
38 )
39
40 Swagger(app, template=template)
41
42
43 @app.route('/colors/<palette>/')
44 def colors(palette):
45 """Example endpoint return a list of colors by palette
46 This is using docstring for specifications
47 ---
48 tags:
49 - colors
50 parameters:
51 - name: palette
52 in: path
53 type: string
54 enum: ['all', 'rgb', 'cmyk']
55 required: true
56 default: all
57 description: Which palette to filter?
58 operationId: get_colors
59 consumes:
60 - application/json
61 produces:
62 - application/json
63 security:
64 colors_auth:
65 - 'write:colors'
66 - 'read:colors'
67 schemes: ['http', 'https']
68 deprecated: false
69 externalDocs:
70 description: Project repository
71 url: http://github.com/rochacbruno/flasgger
72 definitions:
73 Palette:
74 type: object
75 properties:
76 palette_name:
77 type: array
78 items:
79 $ref: '#/definitions/Color'
80 Color:
81 type: string
82 responses:
83 200:
84 description: A list of colors (may be filtered by palette)
85 schema:
86 $ref: '#/definitions/Palette'
87 examples:
88 rgb: ['red', 'green', 'blue']
89 """
90 all_colors = {
91 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
92 'rgb': ['red', 'green', 'blue']
93 }
94 if palette == 'all':
95 result = all_colors
96 else:
97 result = {palette: all_colors.get(palette)}
98
99 return jsonify(result)
100
101
102 def test_swag(client, specs_data):
103 """
104 This test is runs automatically in Travis CI
105
106 :param client: Flask app test client
107 :param specs_data: {'url': {swag_specs}} for every spec in app
108 """
109 for url, spec in specs_data.items():
110 assert 'Palette' in spec['definitions']
111 assert 'Color' in spec['definitions']
112 assert 'colors' in spec['paths']['/colors/{palette}/']['get']['tags']
113 assert spec['schemes'] == ['http']
114 assert spec['foo'] == 'Bar'
115
116
117 if __name__ == "__main__":
118 app.run(debug=True)