django restframework 快速入門python
pip install django pip install djangorestframework
django-admin.py startproject tutorial . # Note the trailing '.' character cd tutorial django-admin.py startapp quickstart
使用pycharm的話這些命令都是不用手動去敲的,可是你要會這些知識數據庫
python manage.py migrate python manage.py createsuperuser --email admin@example.com --username admin
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')
顯示超鏈接,繼承serializers.HyperlinkedModelSerializer,model那個表,fields是要序列那些字段django
from django.contrib.auth.models import User, Group from rest_framework import viewsets from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer
from django.conf.urls import url, include from rest_framework import routers from tutorial.quickstart import views # 下面是自動配置urls 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 browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]api
INSTALLED_APPS = ( ... 'rest_framework', )
python manage.py runserver
瀏覽器訪問 http://127.0.0.1:8000/users/瀏覽器