首页 > 其他分享 >Django rest framework

Django rest framework

时间:2023-01-01 09:00:11浏览次数:34  
标签:rest django framework install pip import Django

环境:

  事先安装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.
# 定义表现形式
class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User # 此处可以换成自己项目的自定义用户表 fields = ['url', 'username', 'email', 'is_staff']

视图:

创建视图集合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接口登录验证

]

 

标签:rest,django,framework,install,pip,import,Django
From: https://www.cnblogs.com/beichengshiqiao/p/17017712.html

相关文章