zoukankan      html  css  js  c++  java
  • 创建一个DjangRestFramework应用

    1. 创建一个Django项目,最终项目结构如下:

    screenshot_1.png

    1. 安装djangorestframework
    pip install djangorestframework
    
    1. 应用目录App下urls.py设计
    # -*-coding:utf-8-*-
    from rest_framework.routers import DefaultRouter
    
    from App import views
    
    router = DefaultRouter()
    router.register(r'api/students', views.StudentViewSet)
    
    1. 项目目录DEFBlog下配置djangorestframework
    • 4.1 配置settings.py, 将'rest_framework'加入到INSTALLED_APPS
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'App.apps.AppConfig',
        'rest_framework',
    ]
    
    • 4.2 配置urls.py
    from django.contrib import admin
    from django.urls import path, include
    
    from App.urls import router
    
    urlpatterns = [
        path('', include(router.urls)),
        # path('admin/', admin.sitsse.urls),
    ]
    
    1. 应用目录App下,models.py设计
    from django.db import models
    
    
    class Student(models.Model):
        name = models.CharField(max_length=32)
    
    1. 应用目录App下, serializers.py设计
    # -*-coding:utf-8-*-
    from rest_framework import serializers
    
    from App.models import Student
    
    
    class StudentSerializer(serializers.ModelSerializer):
        class Meta:
            model = Student
            fields = '__all__'
    
    1. 应用目录App下, views.py
    # -*-coding:utf-8-*-
    from rest_framework.viewsets import ModelViewSet
    
    from App.models import Student
    from App.serializers import StudentSerializer
    
    
    class StudentViewSet(ModelViewSet):
        queryset = Student.objects.all()
        serializer_class = StudentSerializer
    
    1. postman调用效果如下:

    screenshot_1.png

  • 相关阅读:
    js 数据图表
    yii query builder
    mysql if
    这又是起点
    [cookie篇]从cookie-parser中间件说起
    How to find and fix Bash Shell-shock vulnerability CVE-2014-6271 in unix like system
    AngularJS打印问题
    笔记本上班时间自动静音下班自动打开
    SCP命令
    Installing Ruby 1.9.3 on Ubuntu 12.04 Precise Pengolin (without RVM)
  • 原文地址:https://www.cnblogs.com/iread9527/p/12832855.html
Copyright © 2011-2022 走看看