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(r'snippets/(?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加深记忆-加了API_ROOT及超链接的CASE
urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patter ...
- 使用Flask设计带认证token的RESTful API接口
大数据时代 Just a record. 使用Flask设计带认证token的RESTful API接口[翻译] 上一篇文章, 使用python的Flask实现一个RESTful API服务器端 简 ...
- MVC用户登陆验证及权限检查(Form认证)
1.配置Web.conf,使用Form认证方式 <system.web> <authentication mode="None" /> ...
- 从 "org.apache.hadoop.security.AccessControlException:Permission denied: user=..." 看Hadoop 的用户登陆认证
假设远程提交任务给Hadoop 可能会遇到 "org.apache.hadoop.security.AccessControlException:Permission denied: use ...
- Spring boot 入门(四):集成 Shiro 实现登陆认证和权限管理
本文是接着上篇博客写的:Spring boot 入门(三):SpringBoot 集成结合 AdminLTE(Freemarker),利用 generate 自动生成代码,利用 DataTable 和 ...
- 使用Flask设计带认证token的RESTful API接口[翻译]
上一篇文章, 使用python的Flask实现一个RESTful API服务器端 简单地演示了Flask实的现的api服务器,里面提到了因为无状态的原则,没有session cookies,如果访问 ...
- Flask设计带认证token的RESTful API接口[翻译]
上一篇文章, 使用python的Flask实现一个RESTful API服务器端 简单地演示了Flask实的现的api服务器,里面提到了因为无状态的原则,没有session cookies,如果访问 ...
- Apsara Clouder专项技能认证:实现调用API接口
一.API 简介 1.API 的概念 API(Application Programming Interface应用程序编程接口)是一些预定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访 ...
- REST_FRAMEWORK加深记忆-极致抽象,极致完结
余下的就是静心看官方文档了. 这个是最抽象的了. urls.py """tutorial URL Configuration The `urlpatterns` list ...
随机推荐
- Windows Phone 8.1开发:如何让ListView滚动到顶部,回到第一条?
Windows Phone 8.1开发中,ListView向下滑动了半天,用户如果突然想回头看看第一条数据怎么办? 如何让listView滚动到顶部,回到第一条? 很简单,一行代码.调用ListVie ...
- CSS3实现半像素边框
一.思路 普通的1px黑色实线边框: border: 1px solid #000; 半像素边框当然不是简单地把1px改为0.5px(没测试过,可能会被解析成1或者0),border-width的值只 ...
- win32开发基础
收集的,正在学习... 跟我一起玩Win32开发(1):关于C++的几个要点 跟我一起玩Win32开发(2):完整的开发流程 跟我一起玩Win32开发(3):窗口的重绘 跟我一起玩Win32开发(4) ...
- mongodb的常用操作(二)
继续mongodb的学习: 9.mongodb条件查询 假设有user集合,里面结构如下:{ "_id" : ObjectId("52ab35d281181f853264 ...
- nginx配置:支持phpfastcgi,nginx和php-cgi通信,部分nginx常量解释
支持phpfastcgi的配置如下: server { listen 8000; server_name localhost; root F:/home/projects/test; i ...
- Spannable相关方法
实现文本链接 其中tv是TextView类型的控件.只需写java代码即可实现链接,无需在xml文件中进行其他的设置. SpannableString spanTxt = new SpannableS ...
- Android emulator warning----Emulator window was out of view and was recentred
最近在打开Android emulator时,总会提示“Emulator window was out of view and was recentred ”,然后无法打开模拟器,但是可以使用Win7 ...
- Asp.net MVC知识积累
一.知识积累 http://yuangang.cnblogs.com/ 跟蓝狐学mvc教程专题目录:http://www.lanhusoft.com/Article/169.html 依赖注入:htt ...
- Python中处理时间 —— time模块
time模块 time 模块可用来处理时间,详细的说明参考 time模块说明. 逝去的秒数 逝去的秒数表示从某个时间(Python中是"Thu Jan 1 07:00:00 1970&quo ...
- require.js入门指南(二)
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...