DRF-About
introduction
django-rest-framework,是一套基于Django 的 REST 框架,是一个强大灵活的构建 Web API 的工具包。
The Web browsable API is a huge usability win for your developers.
Authentication policies including packages for OAuth1a and OAuth2.
Serialization that supports both ORM and non-ORM data sources.
Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
Extensive documentation, and great community support.
Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
architecture
因为django-rest-framework的主要功能是构建Web API,所以其在django的MTV架构基础上,去除了用于界面显示的模板模块,而在models模块上添加了一层serializers,主要对数据进行序列化和反序列化。对View层进行了扩展,包括View和ViewSet。主要框架变化可以由下图简单表示:
后面的文章会围绕着这个架构图自下而上对DRF框架进行介绍。
包括:
用于序列化和反序列化的
Serializers
;用于构建api的VieW和ViewSet;
从客户端(Web Brower)发来的Request和返回给客户端的Response;
以及隐藏在框架中的认证与权限。
Requirements
- Python (2.7, 3.4, 3.5, 3.6, 3.7)
- Django (1.11, 2.0, 2.1)
Installation
包安装:
pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support
添加至应用列表:
INSTALLED_APPS = ( ... 'rest_framework', )
Example
让我们用一个简单的例子来对DRF进行一个粗略的了解
确认Installation中的配置都已完成;
DRF api 的任何全局设置都保留在
settings.py
文件的一个名为REST_FRAMEWORK
的配置字典中:REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }
在
urls.py
中创建我们的API(真实项目中不会全部放在urls.py文件中,这里只是个例子):from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # 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')) ]
接下来,启动django项目,然后访问 http://127.0.0.1:8000/
, 可以看到我们的DRF界面:
如果确定项目中已添加用户,可以再访问http://127.0.0.1:8000/users/
等其他接口试试。