15.django之Django-Rest-Framework
生活随笔
收集整理的這篇文章主要介紹了
15.django之Django-Rest-Framework
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.首先安裝Django-Rest-Framework
pip3 install djangorestframework pip3 install markdown Markdown為可視化 API 提供了支持 pip3 install django-filter2.使用pycharm創建一個工程和一個app
工程名:restful
app名:api
數據庫默認使用sqlite3
3.配置rest_framework
打開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.同步數據庫
python manage.py makemigrations python manage.py migrate5.序列化
在api下面創建serializers.py文件添加from django.contrib.auth.models import User, Group from rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = Userfields = ('url', 'username', 'email', 'groups')class GroupSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = Group#顯示的字段fields = ('url', 'name')6.添加視圖
在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, GroupSerializerclass UserViewSet(viewsets.ModelViewSet):"""允許查看和編輯user 的 API endpoint"""queryset = User.objects.all()serializer_class = UserSerializerclass GroupViewSet(viewsets.ModelViewSet):"""允許查看和編輯group的 API endpoint"""queryset = Group.objects.all()serializer_class = GroupSerializer7.設置url
在restful下面urlsfrom django.conf.urls import url,include from django.contrib import adminurlpatterns = [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 viewsrouter = 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.啟動訪問
轉載于:https://www.cnblogs.com/liu-yao/p/6058488.html
總結
以上是生活随笔為你收集整理的15.django之Django-Rest-Framework的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sqlserver字符串多行合并为一行
- 下一篇: OLTP与OLAP