(2)python引數

RomanceSky發表於2018-05-30

緊跟前一篇程式碼

關鍵字引數 *args: 接受一個元組 **kwargs: 接受一個字典

from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from accounts.serializers import UserSerializer, GroupSerializer
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from knox.auth import TokenAuthentication
from knox.models import AuthToken
from rest_framework.permissions import IsAuthenticated, AllowAny

class UserViewSet(viewsets.ModelViewSet):
    authentication_classes = (
        TokenAuthentication,
    )
    permission_classes = (AllowAny,)
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        auth_token = AuthToken.objects.create(user)
        data = serializer.data
        ret, *result = data
        print(data)
        print(ret)
        print(*result)
        # print(auth_token)
        return Response(
            {
                "email": user.email,
                "token": auth_token,
                "id": user.id,
                #"key": auth_token.key,
            }
        )
        
測試
圖https://note.youdao.com/yws/res/32077/WEBRESOURCEab3d3d1960a5e92f762fddb0a0345609
結果

(0.001) SELECT "auth_group"."id", "auth_group"."name" FROM "auth_group" INNER JOIN "auth_user_groups" ON ("auth_group"."id" = "auth_user_groups"."group_id") WHERE "auth_user_groups"."user_id" = 22; args=(22,)
{'url': 'http://127.0.0.1:8000/users/22/', 'username': 'sky312', 'email': '', 'groups': []}
url
username email groups
[30/May/2018 08:26:41] "POST /users/ HTTP/1.1" 200 95

複製程式碼

相關文章