Django Restful Framework
1. 下载安装
pip install djangorestframework
pip install markdown
pip install django-filter
或者直接从github上下载项目
git clone
git@github.com:encode/django-rest-framework.git
2. 项目支持
打开自己的Django项目,在项目配置文件settings.py中,添加应用配置
INSTALLED_APPS =(
…
‘rest_framework’
)
在项目根路由中,添加restframework认证路由
INSTALLED_APPS = [
......
'rest_framework',
]
3. 操作案例
第一个案例,创建一个基于数据模型操作的api接口
完成对用户数据的读写操作
rest framework任何配置都是基于全局的REST_FRAMEWORK配置选项,打开你的Django项目配置文件settings.py,添加如下配置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASS': [
'rest_framework.permissions.DjangoModelPermissionOrAnonReadOnly'
]
}
备注:别忘记在你的INSTALLED_APPS中添加rest_framework哦!
接下来,在我们的主路由urls.py中,添加数据模型的处理方式,如下:
"""myrest_ex01 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'is_staff']
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api_auth/', include('rest_framework.urls')),
]
4. 运行测试
打开浏览器,访问http://localhost:8000,就可以看到restful接口描述了
PS:由于手工编写之后编辑器渲染时可能会出现代码渲染缩进出错,所以大家在看代码的过程中尽量注意!
作者:大牧莫邪
链接:https://www.imooc.com/article/40829
文章同步:慕课网