REST_FRAMEWORK加深记忆-加了用户登陆认证,自定义权限的API接口

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了REST_FRAMEWORK加深记忆-加了用户登陆认证,自定义权限的API接口相关的知识,希望对你有一定的参考价值。

哈哈,终于快结束了。。

urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r^admin/, include(admin.site.urls)),
    url(r^, include(snippets.urls)),
]

urlpatterns += [
    url(r^api-auth/, include(rest_framework.urls,
                               namespace=rest_framework))
]
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
    url(r^snippets/$, views.SnippetList.as_view()),
    url(rsnippets/(?P<pk>[0-9]+)/$, views.SnippetDetail.as_view()),
    url(r^users/$, views.UserList.as_view()),
    url(r^users/(?P<pk>[0-9]+)/$, views.UserDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

 

models.py

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())


class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default=‘‘)
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default=python, max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default=friendly, max_length=100)
    owner = models.ForeignKey(auth.User, blank=True, null=True, related_name=snippets)
    highlighted = models.TextField(blank=True, null=True)

    def save(self, *args, **kwargs):
        """
        Use the `pygments` library to create a highlighted HTML
        representation of the code snippet.
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and table or False
        options = self.title and {title: self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)

    class Meta:
        ordering = (created,)

 

permissions.py

__author__ = CHENGANG882
from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.owner == request.user

 

views.py

from snippets.models import Snippet
from snippets.permissions import IsOwnerOrReadOnly
from snippets.serializers import SnippetSerializer
from snippets.serializers import UserSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework import permissions


class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

 

serializers.py

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User


class SnippetSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source=owner.username)

    class Meta:
        model = Snippet
        fields = (id, title, code, linenos, language, style, owner)


class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = (id, username, snippets)

 

以上是关于REST_FRAMEWORK加深记忆-加了用户登陆认证,自定义权限的API接口的主要内容,如果未能解决你的问题,请参考以下文章

REST_FRAMEWORK加深记忆-第二次练习官方文档

加了料的报错注入(实验吧)

java基于token验证之登陆验证

加了域的电脑如何绕过登陆修改密码

super staticfinal关键字加深记忆哦!还有父子类构造函数调用问题

重新温习,不但可以让自己对js更加的深刻认识,又能加深记忆,至此每天一次复习记录在此。