我正在使用Django REST framework编写一个 REST API 。API 将成为社交移动应用程序的后端。按照教程完成后,我可以序列化所有模型,并且可以创建新资源并更新它们。
我正在使用 AuthToken 进行身份验证。
我的问题是:
获得/users
资源后,我希望应用用户能够注册。那么,拥有一个单独的资源是否更好,/register
或者允许匿名用户发布到/users
新资源?
此外,有关权限的一些指导会很棒。
我正在使用Django REST framework编写一个 REST API 。API 将成为社交移动应用程序的后端。按照教程完成后,我可以序列化所有模型,并且可以创建新资源并更新它们。
我正在使用 AuthToken 进行身份验证。
我的问题是:
获得/users
资源后,我希望应用用户能够注册。那么,拥有一个单独的资源是否更好,/register
或者允许匿名用户发布到/users
新资源?
此外,有关权限的一些指导会很棒。
Django REST Framework 3允许序列化程序中的覆盖create
方法:
from rest_framework import serializers
from django.contrib.auth import get_user_model # If used custom user model
UserModel = get_user_model()
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create_user(
username=validated_data['username'],
password=validated_data['password'],
)
return user
class Meta:
model = UserModel
# Tuple of serialized model fields (see link [2])
fields = ( "id", "username", "password", )
继承自的类的序列化字段ModelSerializer
必须在Meta
Django Rest Framework v3.5和最新版本中明确声明。
文件api.py:
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model # If used custom user model
from .serializers import UserSerializer
class CreateUserView(CreateAPIView):
model = get_user_model()
permission_classes = [
permissions.AllowAny # Or anon users can't register
]
serializer_class = UserSerializer
我继续制作自己的自定义视图来处理注册,因为我的序列化程序不希望显示/检索密码。我使 url 与 /users 资源不同。
我的网址配置:
url(r'^users/register', 'myapp.views.create_auth'),
我的观点:
@api_view(['POST'])
def create_auth(request):
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
User.objects.create_user(
serialized.init_data['email'],
serialized.init_data['username'],
serialized.init_data['password']
)
return Response(serialized.data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
我可能错了,但您似乎不需要限制此视图的权限,因为您想要未经身份验证的请求......
最简单的解决方案,在 DRF 3.x 中工作:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password', 'email', 'first_name', 'last_name')
write_only_fields = ('password',)
read_only_fields = ('id',)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
无需其他更改,只需确保未经身份验证的用户具有创建新用户对象的权限即可。
write_only_fields
将确保不显示密码(实际上是我们存储的哈希值),而覆盖create
方法确保密码不是以明文形式存储,而是作为哈希值存储。
我通常像对待任何其他需要授权的 API 端点一样对待用户视图,除了我只是用我自己的 POST(又名创建)覆盖视图类的权限集。我通常使用这种模式:
from django.contrib.auth import get_user_model
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
class UserViewSet(viewsets.ModelViewSet):
queryset = get_user_model().objects
serializer_class = UserSerializer
def get_permissions(self):
if self.request.method == 'POST':
self.permission_classes = (AllowAny,)
return super(UserViewSet, self).get_permissions()
为了更好地衡量,这是我通常使用的序列化程序:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = (
'id',
'username',
'password',
'email',
...,
)
extra_kwargs = {
'password': {'write_only': True},
}
def create(self, validated_data):
user = get_user_model().objects.create_user(**validated_data)
return user
def update(self, instance, validated_data):
if 'password' in validated_data:
password = validated_data.pop('password')
instance.set_password(password)
return super(UserSerializer, self).update(instance, validated_data)
djangorestframework 3.3.x / Django 1.8.x
我更新了 Cahlan 的答案以支持来自 Django 1.5 的自定义用户模型,并在响应中返回用户的 ID。
from django.contrib.auth import get_user_model
from rest_framework import status, serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
@api_view(['POST'])
def register(request):
VALID_USER_FIELDS = [f.name for f in get_user_model()._meta.fields]
DEFAULTS = {
# you can define any defaults that you would like for the user, here
}
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
user_data = {field: data for (field, data) in request.DATA.items() if field in VALID_USER_FIELDS}
user_data.update(DEFAULTS)
user = get_user_model().objects.create_user(
**user_data
)
return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
到目前为止,所有答案都创建了用户,然后更新了用户的密码。这会导致两次数据库写入。为避免额外不必要的数据库写入,请在保存之前设置用户密码:
from rest_framework.serializers import ModelSerializer
class UserSerializer(ModelSerializer):
class Meta:
model = User
def create(self, validated_data):
user = User(**validated_data)
# Hash the user's password.
user.set_password(validated_data['password'])
user.save()
return user
基于 Python 3、Django 2 和 Django REST Framework 视图集的实现:
文件:serializers.py
from rest_framework.serializers import ModelSerializers
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class UserSerializer(ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create_user(
username=validated_data['username'],
password=validated_data['password'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
)
return user
class Meta:
model = UserModel
fields = ('password', 'username', 'first_name', 'last_name',)
文件views.py:
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from django.contrib.auth import get_user_model
from .serializers import UserSerializer
class CreateUserView(CreateModelMixin, GenericViewSet):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
文件urls.py
from rest_framework.routers import DefaultRouter
from .views import CreateUserView
router = DefaultRouter()
router.register(r'createuser', CreateUserView)
urlpatterns = router.urls
聚会有点晚了,但可能会帮助不想编写更多代码行的人。
我们可以使用该super
方法来实现这一点。
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
write_only=True,
)
class Meta:
model = User
fields = ('password', 'username', 'first_name', 'last_name',)
def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
if 'password' in validated_data:
user.set_password(validated_data['password'])
user.save()
return user
虽然这个问题有很多答案,但没有一个答案(截至我撰写本文时)解决了关键的安全问题,即settings.AUTH_PASSWORD_VALIDATORS
. 因此,可以创建一个'1'
不能接受的密码。所以我已经解决了这个主要的安全问题。这是我的解决方案:
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
class SignupSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ['username', 'first_name', 'last_name', 'email', 'password', ]
extra_kwargs = {
'password': {'write_only': True}
}
def validate_password(self, value):
validate_password(value)
return value
def create(self, validated_data):
user = get_user_model()(**validated_data)
user.set_password(validated_data['password'])
user.save()
return user
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated
from . import forms, serializers
class SignupViewSet(mixins.CreateModelMixin,
viewsets.GenericViewSet):
permission_classes = [AllowAny]
serializer_class = serializers.SignupSerializer
现在,如果您尝试使用简单的密码,如'1'
,将自动返回此响应:
{
"password": [
"This password is too short. It must contain at least 8 characters.",
"This password is too common.",
"This password is entirely numeric."
]
}
如果密码像'12345678'
,则响应为:
{
"password": [
"This password is too common.",
"This password is entirely numeric."
]
}
这样,终端客户端将确切地知道密码有效还需要什么。
# This work nicely, but serializer will reamain as it is, like
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
class SignupSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ['username', 'first_name', 'last_name', 'email', 'password', ]
extra_kwargs = {
'password': {'write_only': True}
}
def validate_password(self, value):
validate_password(value)
return value
def create(self, validated_data):
user = get_user_model()(**validated_data)
user.set_password(validated_data['password'])
user.save()
return user
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated
from . import forms, serializers
class SignUpUserView(mixins.CreateModelMixin, viewsets.GenericViewSet):
permission_classes = [AllowAny]
queryset = get_user_model().objects.all() #Add this line
serializer_class = SignUpSerializer