参考地址:https://github.com/tomchristie/django-rest-framework/

一般如果在批量修改多的时候,不建议使用,一般在get请求,或者修改单条数据的时候使用;

安装:pip install djangorestframework

要通过rest-framework实现api,settings的配置如下:

INSTALLED_APPS = [
...
'rest_framework', #注册app
] REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}

 

定义rest_urls,test_urls.py

from django.conf.urls import url, include
from rest_framework import routers from Sansa import rest_views
router = routers.DefaultRouter()
router.register(r'users', rest_views.UserViewSet) #生成一条url # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

  

定义rest_views,rest的视图文件,rest_views.py

from Sansa import models
from Sansa import serializer from rest_framework import serializers, viewsets, routers class UserViewSet(viewsets.ModelViewSet):
queryset = models.UserProfile.objects.all() #必须是queryset和serializer_class,是写死的,这里的user因为是我们自定义的,使用需要写自定义的models对象
serializer_class = serializer.UserSerializer

  

创建serializers.py文件,序列化文件,定义对那个models的哪些字段展示,类似以modelform

from Sansa import models
from rest_framework import serializers, viewsets, routers # Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.UserProfile
fields = ('url', 'email', 'name', 'is_staff')

  

最后,需要将rest_urls和django的urls关联起来:urls

from django.conf.urls import url,include
from django.contrib import admin
from Sansa import views urlpatterns = [
url(r'report/$', views.asset_report),
url(r'api/', include('Sansa.rest_urls')), #关联url
url(r'report/asset_with_no_asset_id/$',views.asset_with_no_asset_id),
url(r'^new_assets/approval/$', views.new_assets_approval, name="new_assets_approval"),
]

需要注意,因为user是自定义的,需要在UserProfile的models中添加has_perms()的属性

class UserProfile(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
name = models.CharField(max_length=32)
# date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False) objects = MyUserManager() #实例化类 USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name'] #必须填写的字段 def get_full_name(self):
# The user is identified by their email address
return self.email def get_short_name(self):
# The user is identified by their email address
return self.email def __str__(self): # __unicode__ on Python 2
return self.email def has_perm(self, perm, obj=None): #有没有指定的权限
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True def has_perms(self,perm,obj=None): return True def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True @property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin

好了,上述显示api已经创建就完成了,这样我们就可以仿照上面的内容,将Asset表的接口添加进来

1、serializer.py

from Sansa import models
from rest_framework import serializers, viewsets, routers # Serializers define the API representation. class AssetSerializer(serializers.ModelSerializer): #因为有通过外键关联的字段manufactory,所以不使用超链接
class Meta:
model = models.Asset
depth = 2 #将外键关联的表的第二层内容也展示出来
fields = ('url', 'asset_type','sn', 'manufactory','name', 'create_date') 因为Manufactory在是Asset表的外键,需要单独创建,将其的内容关联展示
class ManufactorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Manufactory
fields = ('url', 'manufactory','support_num', 'memo')

  

2、rest_views.py:创建视图

from Sansa import models
from Sansa import serializer from rest_framework import serializers, viewsets, router class AssetViewSet(viewsets.ModelViewSet):
queryset = models.Asset.objects.all()
serializer_class = serializer.AssetSerializer class ManufactoryViewSet(viewsets.ModelViewSet):
queryset = models.Manufactory.objects.all()
serializer_class = serializer.ManufactorySerializer

3、rest_urls.py

from django.conf.urls import url, include
from rest_framework import routers from Sansa import rest_views
router = routers.DefaultRouter()
router.register(r'users', rest_views.UserViewSet) #生成一条url
router.register(r'assets', rest_views.AssetViewSet) #生成一条url
router.register(r'manufactory', rest_views.ManufactoryViewSet) #生成一条url # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

  

 

 

  

django使用restframework实现安全的api的更多相关文章

  1. CentOS7 + Python3 + Django(rest_framework) + MySQL + nginx + uwsgi 部署 API 开发环境, 记坑篇

    CentOS7 + Python3 + Django(rest_framework) + MySQL + nginx + uwsgi 部署 API 开发环境 CentOS7 + Python3 + D ...

  2. Django 之 restframework 频率组件的使用

    Django 之 restframework 频率组件的使用以及源码分析 频率组件的使用 第一步,先写一个频率类,继承SimpleRateThrottle 一定要在这个类里面配置一个scop='字符串 ...

  3. 【Django】 rest-framework和RestfulAPI的设计

    [rest-framework] 这是一个基于django才能发挥作用的组件,专门用于构造API的. 说到API,之前在其他项目中我也做过一些小API,不过那些都是玩票性质,结构十分简单而且要求的设计 ...

  4. Django之restframework

    启动流程:引入rest_framework APP 在restframework中,GET数据可以通过request.query_params.get(xxx)获取,post数据可以通过request ...

  5. 通过django的rest-framework……(CBV)

    为什么不使用FBV,因为CBV重用性很高 先看一个例子: from django.views.generic.base import View from django.http import Http ...

  6. rest-framework 序列化格式Restful API设计规范

    理解RESTful架构 Restful API设计指南 理解RESTful架构 越来越多的人开始意识到,网站即软件,而且是一种新型的软件. 这种"互联网软件"采用客户端/服务器模式 ...

  7. django使用RestFramework的Token认证

    今天实现的想法有点不正规: Django Rest framework的框架的认证,API都运行良好. 现在是要自己写一个function来实现用户的功能. 而不是用Rest 框架里的APIVIEW这 ...

  8. Python开发【Django】:日志记录、API认证

    日志记录: 调用同一个对象,分别记录错误日志和运行日志 自定义日志类: class Logger(object): __instance = None def __init__(self): self ...

  9. django框架实现restful风格的API开发

    RESTful风格的要求:https://www.cnblogs.com/chichung/p/9933116.html 利用django原生的框架直接做RESTful的API开发是怎样的呢?感受一下 ...

随机推荐

  1. [深度分析] Python Web 开发框架 Bottle

    [深度分析] Python Web 开发框架 Bottle(这个真的他妈的经典!!!) 作者:lhf2009913 Bottle 是一个非常精致的WSGI框架,它提供了 Python Web开发中需要 ...

  2. delphi正则表达式学习笔记(二)

    正则表达式大全 字符 描述 \ 将下一个字符标记为一个特殊字符.或一个原义字符.或一个向后引用.或一个八进制转义符.例如,"n"匹配字符"n"."\n ...

  3. mybatis的插件,挺好支持下

    利用 Mybatis-generator自动生成代码http://www.cnblogs.com/yjmyzz/p/4210554.html Mybatis 通用 Mapper3 https://gi ...

  4. es6基础(2)--解构赋值

    //解构赋值 { let a,b,rest; [a,b]=[1,2]; console.log(a,b); } //数组解构赋值 { let a,b,rest; [a,b,...rest]=[1,2, ...

  5. spring boot使用配置文件内容

    配置文件如下所示: server: port: 8081 context-path: /demo tag: 12 user: name1: mist-dev password: 123 然后可以通过以 ...

  6. mac上使用jmeter录制web项目和手机app

    前言: 最近熟悉jmeter进行带宽测试和并发测试,发现网上大多都是windows版本,自己用的mac,实验后发现大同小异 1.下载,我使用的jmeter3.2的版本,可以在网上下载,不区分mac版和 ...

  7. 【Selenium-WebDriver问题点】chromeDriver和chrome浏览器版本之间的兼容性问题

    今天早晨因为测试需求,将chrome浏览器更新到最新的65版本,结果之前用的chromeDriver测试计划,都跑不通过了, 所以就在网上找了下,mark下. 最新的chromedriver与chro ...

  8. 47.纯 CSS 创作一个蝴蝶标本展示框

    html,body{ margin:; padding:; } body{ height: 100vh; display: flex; justify-content: center; align-i ...

  9. CentOS6.9 网络设置

    一.临时设置IP地址 ifconfig eth0 192.168.42.119 broadcast 192.168.42.129 netmask 255.255.255.0 二.上述方法只能临时生效, ...

  10. leetcode1003

    class Solution: def isValid(self, S: str) -> bool: n = len(S) if n % 3 != 0: return False while n ...