refactor: simplify cookie handling in middleware

- Updated LanguageMiddleware and UserIdentityMiddleware to always set cookies for language and user ID, respectively, removing conditional checks for existing cookies. This streamlines the cookie management process and ensures consistent behavior across sessions.
This commit is contained in:
Miu Li 2025-06-18 13:33:39 +08:00
parent 1bd19235e0
commit 068000515a
2 changed files with 17 additions and 18 deletions

7
app.py
View File

@ -88,8 +88,7 @@ class LanguageMiddleware(BaseHTTPMiddleware):
# Continue processing the request # Continue processing the request
response = await call_next(request) response = await call_next(request)
# Set cookie if it's not already set or if it's different # Set cookie
if not request.cookies.get("lang") or request.cookies.get("lang") != lang:
response.set_cookie( response.set_cookie(
key="lang", key="lang",
value=lang, value=lang,
@ -129,11 +128,11 @@ class UserIdentityMiddleware(BaseHTTPMiddleware):
response = await call_next(request) response = await call_next(request)
# Set cookie if it's not already set # Set cookie if it's not already set
if not request.cookies.get("user_id"):
response.set_cookie( response.set_cookie(
key="user_id", key="user_id",
value=user_id, value=user_id,
max_age=None, # Cookie will never expire max_age=365 * 24 * 60 * 60, # 1 year
httponly=True, httponly=True,
samesite="lax" samesite="lax"
) )

View File

@ -54,7 +54,7 @@ def new_user() -> int:
user = User() user = User()
user.last_seen = user.created_at = datetime.now(UTC) user.last_seen = user.created_at = datetime.now(UTC)
db.add(user) db.add(user)
db.flush() db.commit()
return user.id return user.id
finally: finally:
db.close() db.close()