• djangorestframework学习1-通过HyperlinkedModelSerializer,ModelViewSet,routers编写第一个接口


    前提首先安装了django,安装方式:pip install django

    1、 djangorestftamework安装:

    pip install djangorestframework

     

    2、 创建一个项目

    django-admin startproject djangorestdemo

     

    3、 创建应用

    cd djangorestdemo

    python  manage.py startapp rest

     

    4、 在settings.py里配置

     

    REST_FRAMEWORK={
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
        ]
    }
    

    5、在djangorestdemo/urls.py编写相关代码

    #编写序列化类
    from django.contrib import admin
    from django.urls import path
    from django.conf.urls import url, include
    from rest_framework import serializers,viewsets,routers
    from django.contrib.auth.models import User
    
    class UserSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model=User
            fields=['url', 'username', 'email', 'is_staff']
    
    #编写viewset视图集
    class UserViewset(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer
    
    
    #注册路由信息
    router=routers.DefaultRouter()
    router.register(r'users',UserViewset)
    
    #urlpatterns里添加路由
    urlpatterns = [
        url('admin/', admin.site.urls),
        url(r'^',include(router.urls)),
        url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    ]
    

     6、运行:python manage.py runserver

    7、浏览器上访问接口

    8、整个工程结构:

     

     

    路漫漫其修远兮,吾将上下而求索
  • 相关阅读:
    Distribution of Data Through OCAF Tree
    OpenCASCADE Application Framework Data Framework Services
    OpenCascade Application Framework Introduction
    被限制的加法(高精入门)
    凝视
    第二题
    图论3 二分图匹配
    图论2 最近公共祖先LCA
    图论1 Tarjan算法
    最小生成树
  • 原文地址:https://www.cnblogs.com/pingchangxinketang/p/13197848.html
Copyright © 2020-2023  润新知