Debian Codegraph @

examples/decorators_in_init_app.py

raw symbols SCIP
1 """
2 A slight variation of the basic auth example to demonstrate using the
3 "decorators" parameter in init_app, instead of during Swagger object
4 creation itself.
5 This is useful in cases when the application factory pattern is used in your
6 flask app.
7 The example is very similar to the basic_auth example, except that the
8 decorators parameter is passed in init_app.
9 Doc for the original basic auth example follows.
10
11 An example that uses HTTP Basic Auth to protect the /apidocs and
12 /apispec_1.json endpoints.
13
14 In this example the login credentials to view the Swagger docs are as follows:
15
16 Username: guest
17 Password: secret
18
19 Failing to provide the right credentials results in a 401 Unauthorized
20 response from all the Flasgger endpoints.
21 """
22 from flask import Flask, request, redirect, Response, jsonify
23 from functools import wraps
24
25 from flasgger import Swagger
26
27
28 def requires_basic_auth(f):
29 """Decorator to require HTTP Basic Auth for your endpoint."""
30
31 def check_auth(username, password):
32 return username == "guest" and password == "secret"
33
34 def authenticate():
35 return Response(
36 "Authentication required.", 401,
37 {"WWW-Authenticate": "Basic realm='Login Required'"},
38 )
39
40 @wraps(f)
41 def decorated(*args, **kwargs):
42 # NOTE: This example will require Basic Auth only when you run the
43 # app directly. For unit tests, we can't block it from getting the
44 # Swagger specs so we just allow it to go thru without auth.
45 # The following two lines of code wouldn't be needed in a normal
46 # production environment.
47 if __name__ != "__main__":
48 return f(*args, **kwargs)
49
50 auth = request.authorization
51 if not auth or not check_auth(auth.username, auth.password):
52 return authenticate()
53 return f(*args, **kwargs)
54
55 return decorated
56
57
58 app = Flask(__name__)
59 app.config["SWAGGER"] = {
60 "title": "Swagger Basic Auth App",
61 "uiversion": 2,
62 }
63 swag = Swagger(
64 template={
65 "swagger": "2.0",
66 "info": {
67 "title": "Swagger Basic Auth App",
68 "version": "1.0",
69 },
70 "consumes": [
71 "application/json",
72 ],
73 "produces": [
74 "application/json",
75 ],
76 },
77 )
78 # passing decorators in init_app
79 swag.init_app(app, decorators=[requires_basic_auth])
80
81
82 @app.route("/echo/<name>", methods=["GET", "POST"])
83 def echo(name):
84 """
85 Echo back the name and any posted parameters.
86 ---
87 tags:
88 - echo
89 parameters:
90 - in: path
91 name: name
92 type: string
93 required: true
94 - in: body
95 name: body
96 description: JSON parameters.
97 schema:
98 properties:
99 first_name:
100 type: string
101 description: First name.
102 example: Alice
103 last_name:
104 type: string
105 description: Last name.
106 example: Smith
107 dob:
108 type: string
109 format: date
110 description: Date of birth.
111 example: 1990-01-01
112 comment:
113 type: string
114 description: Something arbitrary.
115 example: Hello world
116 responses:
117 200:
118 description: OK.
119 """
120 data = {
121 "url_name": name,
122 "json": request.json,
123 }
124 return jsonify(data)
125
126
127 @app.route("/")
128 def index():
129 return redirect("/apidocs")
130
131
132 if __name__ == "__main__":
133 app.run(debug=True)