2017-06-02 6 views
0

(私は最新のdjango/python/DRFを使用しています)使用するDjango Rest Frameworkのスタイル

APIのエンドポイントはアプリケーション内部です。彼らは私がシステムに持っているモデルと1対1でマッチしません。私は、APIのビューを使用する2つの手法を見てきました。私が使用しているよう

最初

は、メソッドを使用しています。

@api_view(['GET', 'POST']) 
@authentication_classes([JSONWebTokenAuthentication]) 
def myApiEndPoint(request): 
    """ 
    This text is the description for this API. 
    """ 

    if request.method == 'GET': 
     return Response("ok get", status=status.HTTP_200_OK) 
    elif request.method == 'POST': 
     return Response("ok post", status=status.HTTP_200_OK) 

目は

class UserViewSet(viewsets.ModelViewSet): 
    """ 
    API endpoint that allows users to be viewed or edited. 
    """ 
    queryset = User.objects.all().order_by('-date_joined') 
    serializer_class = UserSerializer 


class GroupViewSet(viewsets.ModelViewSet): 
    """ 
    API endpoint that allows groups to be viewed or edited. 
    """ 
    queryset = Group.objects.all() 
    serializer_class = GroupSerializer 

第二の方法は、より整然と思わDRFのドキュメントのように、クラス定義を使用しています。しかし:

  1. モデルに特定されていない検証に使用できますか?
  2. このインスタンスでクラス単位のアクセス許可と認証のクラスを定義するにはどうすればよいですか。

おかげ

答えて

0
  1. はい
    • Serializer(ないModelSerializer)に基づくシリアライザを作成して、代わりにあなたのベースクラスの使用などModelViewSetを使用しての
    • がフィールドにカスタム検証を置くviewsets.GenericViewSetGETの場合はlistという名前のメソッドを作成し、POSTの場合はという名前のメソッドを作成します

単にあなたのビューセットでこれらのVARSを定義します:詳細はは、それは非常に簡単ですdocs

  • をビューセットチェック(もauthenticationpermissions

    class UserViewSet(GenericViewSet): 
        permission_classes = [AllowAny, ] # or any other permission class 
        authentication_classes = [JSONWebTokenAuthentication, ] # or any other authentication class 
    
    のためのドキュメントをご確認ください
  • 関連する問題