【发布时间】:2015-11-11 11:22:21
【问题描述】:
我是 DRF 的新手,我想创建一个只能通过使用 Token Auth 标头访问的受保护资源。装饰器@authentication_classes 似乎不起作用。当我发送没有身份验证令牌标头的 GET 请求时 - $ curl http://127.0.0.1:8000/api/users/customers/2,
我仍然得到响应 -
{"id":2,"person":{"id":2,"user":{"id":2,"mobile_number":"9999999999"},"first_name":"Yo","last_name":"Yolo","gender":"M"},"email":"b@b.com"}
我错过了什么?
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)
【问题讨论】:
标签: python django django-rest-framework tastypie django-authentication