python rest_framework.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python rest_framework.py相关的知识,希望对你有一定的参考价值。

from rest_framework.authentication import BaseAuthentication
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import BasePermission
from rest_framework.response import Response


class SessionAuthenticationWithoutCSRF(BaseAuthentication):
    def authenticate(self, request):
        request = request._request
        user = getattr(request, 'user', None)

        if not user or not user.is_active:
            return None

        return (user, None)


class IsTeamMember(BasePermission):
    message = 'You are not member of team.'

    def has_permission(self, request, view):
        if request.user.is_authenticated():
            return request.team in request.user.team_set.all()
        return False


class LinkHeaderPagination(LimitOffsetPagination):
    def get_paginated_response(self, data):
        next_url = self.get_next_link()
        previous_url = self.get_previous_link()

        if next_url is not None and previous_url is not None:
            link = '<{next_url}>; rel="next", <{previous_url}>; rel="prev"'
        elif next_url is not None:
            link = '<{next_url}>; rel="next"'
        elif previous_url is not None:
            link = '<{previous_url}>; rel="prev"'
        else:
            link = ''

        link = link.format(next_url=next_url, previous_url=previous_url)
        headers = {'Link': link} if link else {}

        return Response(data, headers=headers)
        

class SetterMixin:
    def create(self, validated_data):
        instance = super().create(validated_data)
        return self.run_setter(instance, validated_data)

    def update(self, instance, validated_data):
        updated_instance = super().update(instance, validated_data)
        self.run_setter(updated_instance, validated_data)

    def run_setter(self, instance, validated_data):
        for key, value in validated_data.items():
            setter_name = 'set_' + key

            setter = getattr(self, setter_name, None)
            if setter:
                setter(instance, value)
                continue

            setter = getattr(instance, setter_name, None)
            if setter:
                setter(value)
                continue

        return instance

以上是关于python rest_framework.py的主要内容,如果未能解决你的问题,请参考以下文章

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python