-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcookies_example.py
More file actions
192 lines (169 loc) · 6.05 KB
/
cookies_example.py
File metadata and controls
192 lines (169 loc) · 6.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""
Cookies and Session Example
This example demonstrates:
- Setting and reading cookies
- Simple session management with cookies
- HTML responses
"""
import time
from webspark.core import View, WebSpark, path
from webspark.http import Context
from webspark.utils import HTTPException
# Simple in-memory session store
sessions = {}
class HomeView(View):
def handle_get(self, ctx: Context):
# Check if user has a session
session_id = ctx.cookies.get("session_id")
user_data = sessions.get(session_id) if session_id else None
if user_data:
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>WebSpark Cookies Example</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 40px; }}
.user-info {{ background: #e7f3ff; padding: 15px; border-radius: 5px; }}
.actions {{ margin-top: 20px; }}
button {{ padding: 10px 15px; margin: 5px; cursor: pointer; }}
</style>
</head>
<body>
<h1>WebSpark Cookies Example</h1>
<div class="user-info">
<h2>Welcome back, {user_data["username"]}!</h2>
<p>Session ID: {session_id}</p>
<p>Login time: {user_data["login_time"]}</p>
</div>
<div class="actions">
<form action="/logout" method="post" style="display: inline;">
<button type="submit">Logout</button>
</form>
</div>
</body>
</html>
"""
else:
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>WebSpark Cookies Example</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.login-form { max-width: 300px; padding: 20px; border: 1px solid #ccc; border-radius: 5px; }
input { width: 100%; padding: 10px; margin: 10px 0; }
button { padding: 10px 15px; cursor: pointer; }
</style>
</head>
<body>
<h1>WebSpark Cookies Example</h1>
<div class="login-form">
<h2>Login</h2>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
"""
ctx.html(html_content)
class LoginView(View):
def handle_post(self, ctx: Context):
# In a real app, you would validate credentials
username = ctx.body.get("username", "") if ctx.body else ""
password = ctx.body.get("password", "") if ctx.body else ""
if not username or not password:
raise HTTPException("Username and password are required", status=400)
# Create a simple session (in a real app, use a proper session library)
import uuid
session_id = str(uuid.uuid4())
sessions[session_id] = {
"username": username,
"login_time": time.strftime("%Y-%m-%d %H:%M:%S"),
}
# Create response with session cookie
ctx.html("""
<!DOCTYPE html>
<html>
<head>
<title>Login Successful</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.message { background: #d4edda; padding: 15px; border-radius: 5px; }
</style>
</head>
<body>
<h1>Login Successful</h1>
<div class="message">
<p>You have been logged in successfully!</p>
<a href="/">Go to home page</a>
</div>
</body>
</html>
""")
ctx.set_cookie(
"session_id",
session_id,
path="/",
max_age=3600,
http_only=True,
secure=ctx.is_secure,
)
class LogoutView(View):
def handle_post(self, ctx: Context):
# Clear session
session_id = ctx.cookies.get("session_id")
if session_id and session_id in sessions:
del sessions[session_id]
# Create response that clears the cookie
ctx.html("""
<!DOCTYPE html>
<html>
<head>
<title>Logged Out</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.message { background: #f8d7da; padding: 15px; border-radius: 5px; }
</style>
</head>
<body>
<h1>Logged Out</h1>
<div class="message">
<p>You have been logged out successfully.</p>
<a href="/">Go to home page</a>
</div>
</body>
</html>
""")
ctx.delete_cookie("session_id")
class SessionInfoView(View):
def handle_get(self, ctx: Context):
session_id = ctx.cookies.get("session_id")
user_data = sessions.get(session_id) if session_id else None
ctx.json(
{
"session_id": session_id,
"user_data": user_data,
"active_sessions": len(sessions),
}
)
# Create the app
app = WebSpark(debug=True)
# Add routes
app.add_paths(
[
path("/", view=HomeView.as_view()),
path("/login", view=LoginView.as_view()),
path("/logout", view=LogoutView.as_view()),
path("/session-info", view=SessionInfoView.as_view()),
]
)
if __name__ == "__main__":
# For development purposes, you can run this with a WSGI server like:
# gunicorn examples.cookies_example:app
print("Cookies and Session Example")
print("Run with: gunicorn examples.cookies_example:app")