Django+RestFramework实现API接口及接口文档并返回json数据

系统:ubuntu18.04 x64
GitHub:https://github.com/xingjidemimi/DjangoAPI.git

安装

pip install django==2.1.5
pip install djangorestframework  # rest api
pip install coreapi pygments markdown # 自动化接口文档

API示例

创建django项目

django-admin startproject DjangoAPI

创建应用

cd DjangoAPI
python manage.py startapp apiApp

项目代码

  • 修改settings.py,添加应用到配置中

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',  # 添加rest_framework应用
        'apiApp',  # 添加apiApp应用
    ]
    
  • 执行数据库迁移

    python manage.py migrate
    
  • 创建管理员,会提示输入用户名:ubuntu,邮箱:[email protected],密码:ubuntu123456

    python manage.py createsuperuser
    
  • 修改/api/models.py,创建数据库模型。

    from django.db import models
    
    
    class Test(models.Model):
        name = models.CharField(u'姓名', max_length=100, default='no_name')
        sex = models.CharField(u'性别', max_length=10, default='male')
        age = models.CharField(u'年龄', max_length=3, default='0')
    
        def __unicode__(self):
            return '%d: %s' % (self.pk, self.name)
    

    创建模型后执行:

    python manage.py makemigrations # 生成数据库迁移文件
    python manage.py migrate # 执行数据库迁移
    
  • 修改/api/admin.py,写后台管理代码

    from django.contrib import admin
    from apiApp.models import Test
    # Register your models here.
    
    
    @admin.register(Test)
    class BlogTypeAdmin(admin.ModelAdmin):
        list_display = ('pk', 'name')  # 在后台列表下显示的字段
    
  • 运行项目

    python manage.py runserver
    

    出现如下内容表明成功:

    System check identified no issues (0 silenced).
    January 23, 2019 - 08:28:09
    Django version 2.1.5, using settings 'DjangoAPI.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    

    浏览器输入:

    http://127.0.0.1:8000/ # 出现django成功的界面
    http://127.0.0.1:8000/admin # 进入管理后台
    
  • 序列化模型类,在/api/下创建serializers.py,返回json数据

    from rest_framework import serializers
    from apiApp.models import Test
    
    
    class TestSerializers(serializers.ModelSerializer):
        class Meta:
            model = Test  # 指定的模型类
            fields = ('pk', 'name', 'sex', 'age',)  # 需要序列化的属性
    
  • 修改/api/views.py,视图

    from django.shortcuts import render
    from rest_framework import viewsets
    from apiApp.models import Test
    from apiApp.serializers import TestSerializers
    
    
    class TestViewSet(viewsets.ModelViewSet):
        # 指定结果集并设置排序
        queryset = Test.objects.all().order_by('-pk')
        # 指定序列化的类
        serializer_class = TestSerializers
    
  • 修改/urls.py/,配置主路由

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('apiApp.urls')),  # 添加应用的路由地址
    ]
    
  • 在/api/下创建urls.py,配置应用路由

    from django.conf.urls import include
    from django.urls import path
    from rest_framework import routers
    from apiApp import views
    from rest_framework.documentation import include_docs_urls
    
    
    API_TITLE = 'API Documents'
    API_DESCRIPTION = 'API Information'
    
    
    # 定义路由地址
    route = routers.DefaultRouter()
    
    # 注册新的路由地址
    route.register(r'test', views.TestViewSet)
    
    # 注册上一级的路由地址并添加
    urlpatterns = [
        path('', include(route.urls)),
        # 接口文档路由
        path(r'docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION, authentication_classes=[], permission_classes=[]))
    ]
    
  • 运行项目

    python manage.py runserver
    

    打开浏览器输入:

    http://127.0.0.1:8000 # api主页
    点击主页提供的链接http://127.0.0.1:8000/test进入下一级目录
    http://127.0.0.1:8000/docs进入接口文档
    
  • 使用Postman测试工具测试api数据

    进入ubuntusoftware应用商店,搜索postman进行安装

    在postman中输入http://127.0.0.1:8000/api/student点击send,并返回json数据。

你可能感兴趣的:(Web后端)