DRF-Django rest framework

环境:

  事先安装python、虚拟环境、django,项目的创建省略。

国内清华大学镜像  

pip install python==3.10.5 -i https://pypi.tuna.tsinghua.edu.cn/simple/

pip install virtualenv -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install virtualenvwrapper -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install django==4.1.4 -i https://pypi.tuna.tsinghua.edu.cn/simple/

 

网址:

  https://www.django-rest-framework.org/

 

安装:

pip安装

pip install djangorestframework #DRF
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

 

github安装

git clone https://github.com/encode/django-rest-framework

 

国内豆瓣镜像安装

pip install djangorestframework https://pypi.douban.com/simple

 

注册:

django 项目的 settings.py 文件中进行配置

INSTALLED_APPS = [
    ...
    'rest_framework',
]

 

权限:

  django 项目的  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' # 默认域内全部可以访问,但只能只读
    ]
}

 

总路由:

django 项目的 urls.py设置

urlpatterns = [
    ...
  path('admin/', admin.site.urls),
  path('别名(例如:app1)/', include('app名称.app路由文件名(例如:app1.urls)'))
  
]

 

序列化:

  创建ModelSerializer

django 项目中创建serializers.py文件,名称可以自定义。

from django.contrib.auth.models import User # 此处可以换成自己项目的自定义用户表 from 自己的项目 import models
from rest_framework import serializers
# Serializers define the API representation.
# 定义表现形式
# HyperlinkedModelSerializer 类与 ModelSerializer 类相似,只不过它使用超链接来表示关系而不是主键。HyperlinkedModelSerializer 会自动生成一个 url 字段来表示超链接 class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User # 此处可以换成自己项目的自定义用户表 fields = ['url', 'username', 'email', 'is_staff']

深度depth,设置关联的层级,防止层级太多导致的资源占用过多。  

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User # 此处可以换成自己项目的自定义用户表
        fields = ['url', 'username', 'email', 'is_staff']
     depth=2 # 外键存在多级时,仅关联两级

   # 设置在class Meta:下

   # 我们可以在 extra_kwargs 设置中的 view_name 和 lookup_field

# 来正确配置我们的 URL
# view_name 和 urls.py 中的 name 参数相对应,表示使用哪个 url
# lookup_field 表示用哪个字段来作为 url 的唯一识别标记
# 本例中每个 Profile 的 url 是通过 id 来区分的,所以该字段用 id

extra_kwargs = {
'url': {'view_name': 'profile-detail', 'lookup_field': 'id'},
'owner': {'lookup_field': 'id'}
}

 

视图:

创建视图集合ModelViewSet,并在视图中绑定序列化 

# ViewSets define the view behavior.
from django.contrib.auth.models import User # 此处可以换成自己项目的自定义用户表 from 自己的项目 import models
from rest_framework import viewsets
from 项目名称 import 序列化文件名(例如:serializers)
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

  自定义视图方法

  

 

 

路由:

  创建app的路由文件urls.py

router的设置

# Routers provide an easy way of automatically determining the URL conf.

from django.urls import path, include # 引用path, include
from rest_framework import routers
from 项目名称 import 视图文件(例如:views) 或者 from 项目名称.views import 视图集合中某个ModelViewSet(例如:UserViewSet)
router = routers.DefaultRouter() # 生成router实例
router.register(r'users', UserViewSet) # 注册router实例的视图映射
# 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')) # 用于api接口登录验证

]

 

posted @ 2023-01-01 08:53  侬侬发  阅读(35)  评论(0编辑  收藏  举报