Django 不需要对选项请求进行身份验证
我的设置.pyDjango 不需要对选项请求进行身份验证,django,django-rest-framework,Django,Django Rest Framework,我的设置.py REST_FRAMEWORK = { 'UNICODE_JSON': True, 'NON_FIELD_ERRORS_KEY': '__all__', 'DEFAULT_AUTHENTICATION_CLASSES': ( # TODO(dmu) HIGH: Support OAuth or alike authentication 'rest_framework.authentication.TokenAuthentica
REST_FRAMEWORK = {
'UNICODE_JSON': True,
'NON_FIELD_ERRORS_KEY': '__all__',
'DEFAULT_AUTHENTICATION_CLASSES': (
# TODO(dmu) HIGH: Support OAuth or alike authentication
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'ALLOWED_VERSIONS': ['v1'],
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
执行此操作时,会出现身份验证错误:
curl -X OPTIONS http://127.0.0.1:8000/api/passenger/v1/order/ | python -m json.tool
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 58 0 58 0 0 469 0 --:--:-- --:--:-- --:--:-- 475
{
"detail": "Authentication credentials were not provided."
}
我希望我的服务器响应“模式”描述,而不是必需的身份验证。同时,我希望它像往常一样要求对GET、POST、PUT、PATCH和DELETE请求进行身份验证
我怎样才能做到这一点
我的解决方案
谢谢你,阿拉斯代尔。我个人使用了这个解决方案:
from rest_framework.permissions import DjangoObjectPermissions
OPTIONS_METHOD = 'OPTIONS'
class DjangoObjectPermissionsOrOptions(DjangoObjectPermissions):
def has_permission(self, request, view):
if request.method == OPTIONS_METHOD:
return True
else:
return super(DjangoObjectPermissions, self).has_permission(request, view)
Django rest框架附带了一个permissions类,它允许经过身份验证的用户执行任何请求,而未经授权的用户则可以发出GET、HEAD或OPTIONS请求 您的用例非常相似,因此您可以尝试以下(未经测试):
非常感谢你。你对相关问题有什么想法吗?
class IsAuthenticatedOrOptions(BasePermission):
"""
The request is authenticated as a user, or an OPTIONS request.
"""
def has_permission(self, request, view):
return (
request.method == 'OPTIONS' or
request.user and
request.user.is_authenticated()
)
'DEFAULT_PERMISSION_CLASSES': (
'path.to.IsAuthenticatedOrOptions',
),