django-restframework使用
安装restframework:
pip install djangorestframework
修改项目settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ]
修改项目urls.py:
from rest_framework import routers from olsapp import views router = routers.DefaultRouter() router.register(r'olsapp', views.OlsQuarkViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
修改app的models.py:
#coding:utf-8 from django.db import models # Create your models here. class OlsQuark(models.Model): name = models.CharField(max_length=45, default='',verbose_name='系统名称') nlink = models.CharField(max_length=45, default='',verbose_name='系统内网链接') wlink = models.CharField(max_length=45, blank=True, null=True,default='',verbose_name='系统外网链接') ols_describe = models.CharField(max_length=200, blank=True, null=True,default='', verbose_name='系统描述') class Meta: verbose_name = '业务系统链接' verbose_name_plural = verbose_name def __str__(self): return self.name
新增app的serializers.py文件
from rest_framework import serializers from .models import OlsQuark class OlsQuarkSerializer(serializers.ModelSerializer): class Meta: model = OlsQuark fields = ('name', 'ols_describe', 'nlink', 'wlink')
修改app的views.py:
from django.shortcuts import render from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import OlsQuarkSerializer from .models import OlsQuark class OlsQuarkViewSet(viewsets.ModelViewSet): queryset = OlsQuark.objects.all() serializer_class = OlsQuarkSerializer
启动应用访问:http://*.*.*.*/olsapp/