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数据库请求。
阅读(1766) | 评论(0) | 转发(0) |