Debian Codegraph @

examples/kitchen-sink.py

raw
1 from flask import Flask, session
2 from flask_session import Session
3 from redis.exceptions import RedisError
4
5 app = Flask(__name__)
6 app.config.from_object(__name__)
7 app.config.update(
8 {
9 "SESSION_TYPE": "redis",
10 "SECRET_KEY": "sdfads",
11 "SESSION_SERIALIZATION_FORMAT": "json",
12 }
13 )
14
15 Session(app)
16
17
18 @app.route("/")
19 def index():
20 return "No cookies in this response if it is your first visit."
21
22
23 @app.route("/add-apple/")
24 def set():
25 session["apple_count"] = session.get("apple_count", 0) + 1
26 return "ok"
27
28
29 @app.route("/get-apples/")
30 def get():
31 result = str(session.get("apple_count", "no apples"))
32 return result
33
34
35 @app.route("/login/")
36 def login():
37 # Mitigate session fixation attacks
38 # If the session is not empty (/add-apple/ was previously visited), the session will be regenerated
39 app.session_interface.regenerate(session)
40 # Here you would authenticate the user first
41 session["logged_in"] = True
42 return "logged in"
43
44
45 @app.route("/logout/")
46 def delete():
47 session.clear()
48 return "deleted"
49
50
51 @app.route("/error/")
52 def error():
53 raise RedisError("An error occurred with Redis")
54
55
56 @app.errorhandler(RedisError)
57 def handle_redis_error(error):
58 app.logger.error(f"Redis error encountered: {error}")
59 return "A problem occurred with our Redis service. Please try again later.", 500
60
61
62 if __name__ == "__main__":
63 app.run(debug=True)