1.首先安装Django-Rest-Frameworkpython
pip3 install djangorestframework pip3 install markdown Markdown为可视化 API 提供了支持 pip3 install django-filter
2.使用pycharm建立一个工程和一个appsql
工程名:restful数据库
app名:apidjango
数据库默认使用sqlite3api
3.配置rest_frameworkrestful
打开settings文件 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework' #新增 ] 添加 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), 'PAGINATE_BY': 10 }
4.同步数据库markdown
python manage.py makemigrations python manage.py migrate
5.序列化session
在api下面建立serializers.py文件 添加 from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group #显示的字段 fields = ('url', 'name')
6.添加视图app
在api的views里添加以下代码 from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User, Group from rest_framework import viewsets from api.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ 容许查看和编辑user 的 API endpoint """ queryset = User.objects.all() serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ 容许查看和编辑group的 API endpoint """ queryset = Group.objects.all() serializer_class = GroupSerializer
7.设置urlurl
在restful下面urls from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), #添加 url(r'^api/', include('api.urls')), ] 在api下面建立urls 添加 from django.conf.urls import patterns, url, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. urlpatterns = [ url(r'^', include(router.urls)), #验证登陆使用 url(r'auth',include('rest_framework.urls')) ]
8.启动访问