
文章目录
-
- [关于 DRF](#关于 DRF)
关于 DRF
DRF : Django REST framework
DRF 是一个建立在Django基础之上的Web 应用开发框架,可以快速的开发REST API接口应用。
在REST framework中,提供了序列化器Serialzier的定义,可以帮助我们简化序列化与反序列化的过程,不仅如此,还提供丰富的类视图、扩展类、视图集来简化视图的编写工作。
REST framework还提供了认证、权限、限流、过滤、分页、接口文档等功能支持。
REST framework提供了一个API 的Web可视化界面来方便查看测试接口。
shell
pip install djangorestframework
1、接着上文,我们在 ddemo/settings.py
的 INSTALLED_APPS
添加 rest_framework
app;添加 REST_FRAMEWORK
键
shell
INSTALLED_APPS = [
'django.contrib.admin',
...
'hello',
'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',
]
}
2、编辑 ddemo/urls.py
shell
from django.contrib.auth.models import User
from django.urls import include, path
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 a 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 = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
3、创建用户
shell
python manage.py createsuperuser
这里我添加用户名为 xx,密码为 1234;后面将会用到
你也可以通过这种方式创建用户:
shell
python manage.py createsuperuser --email admin@example.com --username admin
4、运行
shell
python manage.py runserver
5、测试 请求
shell
curl -H 'Accept: application/json; indent=4' -u xx:1234 http://127.0.0.1:8000/users/
http -a admin:password123 http://127.0.0.1:8000/users/
得到:
shell
[
{
"url": "http://127.0.0.1:8000/users/1/",
"username": "xx",
"email": "1625608596@qq.com",
"is_staff": true
}
]
创建新用户,名为 new,邮箱为 new@example.com
shell
curl -X POST -d username=new -d email=new@example.com -d is_staff=false -H 'Accept: application/json; indent=4' -u xx:1234 http://127.0.0.1:8000/users/
返回:
shell
{
"url": "http://127.0.0.1:8000/users/2/",
"username": "new",
"email": "new@example.com",
"is_staff": false,
}