django使用rest_framework 实现web的api接口。
安装pip install djangorestframework
在settings配置文件中设置,加入app和权限设置
-
installed_apps = [
-
-
'django.contrib.admin',
-
'django.contrib.auth',
-
'django.contrib.contenttypes',
-
'django.contrib.sessions',
-
'django.contrib.messages',
-
'django.contrib.staticfiles',
-
'rest_framework',
-
'quick',
-
'blog',
-
]
-
-
rest_framework = {
-
-
'default_permission_classes':(
-
#only allow admin user
-
#'rest_framework.permissions.isadminuser',
-
#use django's standard users permissions,
-
# or allow read-only access for unauthenticated users
-
#'rest_framework.permissions.djangomodelpermissionsoranonreadonly',
-
),
-
-
'page_size':10
-
}
首先实现数据库,models.py
-
class his_comm(models.model):
-
his_id = models.charfield(max_length=10)
-
host_ip = models.genericipaddressfield(default='')
-
his_user = models.charfield(max_length=10)
-
his_time = models.charfield(max_length=20)
-
his_command = models.charfield(max_length=200)
-
-
def __str__(self):
-
return self.his_id
设置数据库接口序列化
serializers.py
-
from rest_framework import serializers
-
from quick.models import his_comm
-
-
class hisserializser(serializers.hyperlinkedmodelserializer):
-
class meta:
-
model = his_comm
-
fields = ('his_id','host_ip','his_user','his_command','his_time')
设置展示序列化数据
views.py
-
from rest_framework import viewsets
-
from serializers import
-
userserializer,groupserializer,hisserializser
-
from quick.models import his_comm
-
-
class hisset(viewsets.modelviewset):
-
queryset = his_comm.objects.all()
-
serializer_class = hisserializser
urls.py设置路由
-
from rest_framework import routers,urls
-
-
-
-
router = routers.defaultrouter()
-
router.register(r'hist',views.hisset)
-
-
urlpatterns = [
-
url(r'^api/', include(router.urls)), #接口api
-
url(r'^api-auth/',include('rest_framework.urls',namespace='rest_framework')), #接口账户认证
-
]
实现了hist的接口实现,当使用post方法时,需要在settings.
rest_framework.default_permission_classes 设置权限。是否允许匿名用户实现post数据库请求。
阅读(1639) | 评论(0) | 转发(0) |