使用DRF框架进行接口测试时,出现“method \PUT\(或\\DELETE\) not allowed!”,经过多方搜索,
问题分析见:
最终发现无外乎以下操作可以尝试解决:
一、修改settings文件
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissions',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
二、在View方法中添加 http_method_names
class RiskView(ModelViewSet):
#响应器
renderer_classes = [JSONRenderer,BrowsableAPIRenderer]
# 分页器=自己写的分页类,不能=列表
pagination_class = CustomPagination
#指定查询表
queryset = Risk.objects.all()
# 指定序列化器
serializer_class = RiskSerializer
http_method_names = ['put','get','delete','post']
此时路径需要如下设置,不然会报下面四的问题:
path(r'risks/', views.RiskView.as_view({'get':'list','post':'create'})),
path(r'risks/detail/<int:pk>/',views.RiskView.as_view({'get': 'retrieve','delete':'destroy','put': 'update'})),
四、列表视图只支持get、详细视图支持更新或删除操作,因此DRF需要知道你想要操作的对象
/api/resource/
/api/resource/1/
path(r'risks/', views.RiskView.as_view({'get':'list','post':'create'})),
path(r'risks/detail/<int:pk>/',views.RiskView.as_view({'get': 'retrieve','delete':'destroy','put': 'update'})),
五、使用过程中还有可能遇到的其它问题
1.默认的viewset和默认的router,但发送put、delete请求提示不支持
官方实现update方法的时候要求传入pk,所以在put时将请求URL改成:path/pk/就可以了。
2.使用put和delete请求方式,结果返回正常,但数据修改未生效
先访问/api-auth/login/登录django,然再操作就可以修改数据了文章来源:https://www.toymoban.com/news/detail-576951.html
参考链接:
https://stackoverflow.com/questions/43529555/how-to-not-allow-the-put-method-at-all-but-allow-patch-in-a-drf-viewset
https://blog.csdn.net/qq_39402334/article/details/83409691
https://www.cnblogs.com/wurijie/p/13339859.html文章来源地址https://www.toymoban.com/news/detail-576951.html
到了这里,关于Method *** Not Allowed 解决办法集锦的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!