我正在尝试使用来自 drf-extensions 的批量更新。为了使其工作,有一个安全措施需要标题“X-BULK-OPERATION”:'true'。我可以使用 curl 或我的 angular 应用程序使应用程序正常工作,但在我的测试中,我试图rest_framework.test.APIClient用来发送 partial_update 请求,但每次我收到 400 响应时,在调试请求时,我都会收到
ipdb> response.data
{'detail': "Header 'X-BULK-OPERATION' should be provided for bulk operation."}
Run Code Online (Sandbox Code Playgroud)
这是我尝试在测试中使用的请求
response = self.client.patch(
'/api/v1/db_items/?active=True',
json.dumps(data),
content_type='application/json',
**{X-BULK-OPERATION: 'true'}
)
Run Code Online (Sandbox Code Playgroud)
有没有办法在 APIClient 请求上设置标头?
我什至尝试更改标题名称并将其设置在凭据中
self.client.credentials(HTTP_BULK_OPERATION='true')
Run Code Online (Sandbox Code Playgroud)
但我每次都会遇到同样的错误
我无法让我的路由器根据“parents_query_lookup”过滤我的请求。
这是我的代码:
网址.py:
from rest_framework_extensions.routers import ExtendedSimpleRouter
from .views import OrganizationViewSet, GroupViewSet, BootGroupViewSet
router = ExtendedSimpleRouter()
(router.register(r'organizations', OrganizationViewSet,
base_name='organization')
.register(r'groups', GroupViewSet, base_name='organizations-group',
parents_query_lookups=['resource__organization'])
.register(r'boot_groups', BootGroupViewSet,
base_name='organizations-groups-boot_group',
parents_query_lookups=['group__resource__organization', 'group']))
urlpatterns = router.urls
Run Code Online (Sandbox Code Playgroud)
视图.py:
from rest_framework.viewsets import ModelViewSet
from rest_framework_extensions.mixins import NestedViewSetMixin
from .models import Organization, OrganizationSerializer, \
Group, GroupSerializer, BootGroup, BootGroupSerializer
class OrganizationViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Organization.objects.all()
serializer_class = OrganizationSerializer
class GroupViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
class BootGroupViewSet(NestedViewSetMixin, ModelViewSet):
queryset = BootGroup.objects.all()
serializer_class = BootGroupSerializer
Run Code Online (Sandbox Code Playgroud)
枚举.py:
class ResourceTypeEnum: …Run Code Online (Sandbox Code Playgroud) 代码如下:
class UserViewSet(ViewSet):
# ... Many other actions
def list(self):
# list implementation
def retrieve(self, request, pk):
# manual pk int validation
router = DefaultRouter()
router.register(r"users", UserViewSet, basename="users")
urlpatterns = router.urls
Run Code Online (Sandbox Code Playgroud)
现在 pk 未验证为 int,因此会向 db 发出请求,这是我想避免的。有什么方法可以在网址中添加这种类型的验证吗?我可以在不使用路由器的情况下实现这一点,如下所示:
urlpatterns = [
path('users/<int:pk>/', UserViewSet.as_view({'get': 'retrieve'}),
# many other actions have to be added seperately
]
Run Code Online (Sandbox Code Playgroud)
但我的视图集中有很多操作,所有操作都必须单独添加。有没有更干净的方法或包?