https://www.django-rest-framework.org/tutorial/quickstart/
https://www.django-rest-framework.org/tutorial/quickstart/
ubuntu16.04
流程:
python3 -m venv env
source env/bin/activate
python -V
Python 3.5.2
更新pip 版本
python -m pip install --upgrade pip
pip install django
pip install django
pip install djangorestframework
pip install django-filter
pip list
Package Version
------------------- -------
Django 2.2.6
django-filter 2.2.0
djangorestframework 3.10.3
pip 19.3.1
pkg-resources 0.0.0
pytz 2019.3
setuptools 20.7.0
sqlparse 0.3.0
mkdir tutorial
cd tutorial
django-admin startproject tutorial
cd tutorial
django-admin startapp quickstart
python manage.py migrate
python manage.py createsuperuser --email admin@example.com --username admin
user named admin with a password of password123
vi quickstart/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']
vi quickstart/views.py
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from 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
vi tutorial/urls.py
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from quickstart 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 browsable API.
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
vi tutorial/settings.py
ALLOWED_HOSTS = ['*']
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
python manage.py runserver 192.168.99.218:8080
#### 运行结果:
http://192.168.99.218:8080/
http://192.168.99.218:8080/groups/
http://192.168.99.218:8080/users/
填入内容,然后点击下面的POST , 可以添加用户.