django-waffle的waffle_status接口无法正确返回用户关联Flag状态
问题原因
waffle默认的waffle_status视图仅支持Session认证,而你通过Postman请求时使用的是DRF的JWT Token认证,原视图无法解析该Token,导致request.user始终为AnonymousUser,因此用户绑定的Flag状态无法正确返回。
你的测试用例能成功,是因为client.force_login()采用的是Session认证方式,符合waffle视图的默认认证逻辑。
解决方案
自定义支持JWT认证的waffle_status视图,替换原路由即可:
- 在你的应用(比如
example)中创建views.py,添加以下代码:
from waffle.views import WaffleJSON from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated class AuthenticatedWaffleJSON(WaffleJSON): # 同时支持JWT和Session认证,兼容前后端不同场景 authentication_classes = [JWTAuthentication, SessionAuthentication] permission_classes = [IsAuthenticated]
- 修改项目根目录的
urls.py,替换原waffle的waffle_status路由:
from django.urls import path, include from waffle.urls import urlpatterns as waffle_urls from example.views import AuthenticatedWaffleJSON # 遍历waffle路由,替换waffle_status视图 for url_entry in waffle_urls: if url_entry.name == "waffle_status": url_entry.callback = AuthenticatedWaffleJSON.as_view() urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/', include([path('', include(example_urls))])), path('waffle/', include(waffle_urls)), ]
- Postman请求时,确保在Headers中正确携带JWT令牌:
Authorization: Bearer <你的access_token>
完成以上配置后,waffle_status视图就能正确识别登录用户,返回对应Flag的激活状态。
内容的提问来源于stack exchange,提问作者SoundWave
相关产品推荐
相关产品推荐

