测试使用环境:Windows10+pycharm+python3.7
参考文章:https://q1mi.github.io/Django-REST-framework-documentation/tutorial/quickstart_zh/
1、pycharm新建项目
2、安装restframework
pip install djangorestframework
3、创建APP
django-admin startapp quickstart
4、数据迁移(数据库同步)
python manage.py migrate
5、创建用户,名为 administrator,密码为 password123
python manage.py createsuperuser
6、详细代码
Settings.py
INSTALLED_APPS = ( ... 'rest_framework', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'PAGE_SIZE': 10 }
urls.py
from django.conf.urls import url, include from rest_framework import routers from quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # 使用自动URL路由连接我们的API。 # 另外,我们还包括支持浏览器浏览API的登录URL。 urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
创建 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')
quickstart/views.py
from django.contrib.auth.models import User, Group from rest_framework import viewsets from quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ 允许用户查看或编辑的API路径。 """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ 允许组查看或编辑的API路径。 """ queryset = Group.objects.all() serializer_class = GroupSerializer
7、项目测试
执行代码,运行程序
python manage.py runserver
打开浏览器,地址栏输入
http://127.0.0.1:8000/users/
点击“Log in”,输入开始时创建的用户的用户名和密码进行登录即可。
后记
如果有免登录的需求,将settings文件中的相应配置更改即可,代码如下:
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.AllowAny', ], 'PAGE_SIZE': 10 }