阿里山QQ

导航

django使用restframework实现安全的api

参考地址: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'))
]

  

 

 

 

  

posted on 2017-03-01 10:54  阿里山QQ  阅读(996)  评论(0编辑  收藏  举报