You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from fastapi.responses import Response
from fastapi.requests import Request
import logging
class CookieUtil:
@staticmethod
def set_cookie(res: Response, key: str, value: str, max_age: int = 3600, path: str = "/", secure: bool = False,
httponly: bool = True):
"""
设置cookie
:param res: FastAPI的Response对象
:param key: cookie的键
:param value: cookie的值
:param max_age: cookie的有效时间默认1小时3600秒
:param path: cookie的路径默认为根路径("/")
:param secure: 是否仅通过HTTPS传输默认False
:param httponly: 是否仅通过HTTP请求访问默认True
"""
res.set_cookie(
key=key,
value=value,
httponly=httponly,
secure=secure,
max_age=max_age,
path=path
)
logging.info(f"设置 cookie: {key}={value}")
@staticmethod
def get_cookie(req: Request, key: str) -> str:
"""
从请求中获取cookie的值
:param req: FastAPI的Request对象
:param key: cookie的键
:return: cookie的值如果未找到则返回None
"""
token_value = req.cookies.get(key)
logging.info(f"从 cookie 中获取的 {key}: {token_value}")
return token_value
@staticmethod
def remove_cookie(res: Response, key: str, path: str = "/"):
"""
移除cookie
:param res: FastAPI的Response对象
:param key: cookie的键
:param path: cookie的路径默认为根路径("/")
"""
res.delete_cookie(key, path=path)
logging.info(f"移除 cookie: {key}")
# 示例使用
if __name__ == "__main__":
# 创建一个示例响应对象
response = Response(content="示例响应")
# 设置一个cookie
CookieUtil.set_cookie(response, key="auth_token", value="your_token_value")
# 创建一个示例请求对象通常从FastAPI请求中获取
request = Request(scope={
"type": "http",
"headers": [
(b"cookie", b"auth_token=your_token_value")
]
})
# 获取cookie
token = CookieUtil.get_cookie(request, key="auth_token")
print(token)
# 移除cookie
CookieUtil.remove_cookie(response, key="auth_token")
# 打印示例响应头
print(response.headers)