0
我是DRF的新手,我想創建一個受保護的資源,只能使用Token Auth頭訪問它。裝飾者@authentication_classes
似乎不起作用。當我送,而不驗證令牌頭的GET請求 - $ curl http://127.0.0.1:8000/api/users/customers/2
,Django Rest框架:無法創建受保護的資源
我仍然得到迴應 -
{"id":2,"person":{"id":2,"user":{"id":2,"mobile_number":"9999999999"},"first_name":"Yo","last_name":"Yolo","gender":"M"},"email":"[email protected]"}
我缺少什麼?
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
urls.py
from rest_framework.authtoken import views as rest_views
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^obtain-auth-token/', rest_views.obtain_auth_token),
url(r'^customers/$', views.register_customer),
url(r'^customers/(?P<pk>[0-9]+)$', views.customer_detail)
]
views.py
@api_view(["GET", "PUT"])
@authentication_classes([authentication.TokenAuthentication])
def customer_detail(request, pk):
try:
customer = Customer.objects.get(pk=pk)
except Customer.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer = CustomerSerializer(customer)
return Response(serializer.data)
elif request.method == "PUT":
customer_serializer = CustomerSerializer(customer, data=request.data)
person_serializer = PersonSerializer(customer.person, data=request.data)
person_valid = person_serializer.is_valid()
customer_valid = customer_serializer.is_valid()
if person_valid and customer_valid:
person_serializer.save()
customer_serializer.save()
return Response(request.data)
else:
errors = {}
errors.update(person_serializer._errors)
errors.update(customer_serializer._errors)
return Response(errors, status=status.HTTP_400_BAD_REQUEST)
文檔:http://www.django-rest-framework.org/api-guide/permissions/ –