Django REST框架是一个用于构建Web API的强大且灵活的工具包
您可能想要使用REST框架的一些原因:
- 可浏览性
- 身份认证
- 支持ORM和非ORM的序列化
- 良好的文档支持
安装初步
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
可选包:
文件配置
在配置文件setting 中添加 APP如下图
INSTALLED_APPS = (
...
'rest_framework',
)
在url 中添加路由如下
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls'))
]
example (例子)
我们来看看使用REST框架构建简单模型支持的API的一个简单例子。
我们将创建一个读写API来访问我们项目用户的信息。
REST框架API的任何全局设置都保存在一个名为的配置字典中REST_FRAMEWORK。首先将以下内容添加到您的settings.py模块中:
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'
]
}
我们准备好现在创建我们的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'))
]