Django REST Framework 實現(xiàn)業(yè)務 api 并自動文檔化

使用MySql替換SQL

業(yè)務場景下,還是需要使用擴展性較好的Mysql等主流數(shù)據(jù)庫,SQL只適合入門調(diào)試使用。

為Django項目創(chuàng)建數(shù)據(jù)庫

create database rouboinfo default charset utf8 collate utf8_general_ci;

配置Django項目的數(shù)據(jù)庫信息

## settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'rouboinfo',
        'USER': 'root',
        'PASSWORD': 'junjian11',
        'HOST': '127.0.0.1'
    }
}
## top __init__.py
import pymysql
pymysql.install_as_MySQLdb()

初始化數(shù)據(jù)庫

python manage.py makemigrations
python manage.py migrate

觀察mysql內(nèi)的數(shù)據(jù)庫是否初始化完成

mysql> use rouboinfo;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_rouboinfo        |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
10 rows in set (0.00 sec)

Django ORM 實踐

Django通過自定義Python類的形式來定義具體的模型,每個模型的物理存在方式就是一個Python的類Class,每個模型代表數(shù)據(jù)庫中的一張表,每個類的實例代表數(shù)據(jù)表中的一行數(shù)據(jù),類中的每個變量代表數(shù)據(jù)表中的一列字段。Django通過模型,將Python代碼和數(shù)據(jù)庫操作結(jié)合起來,實現(xiàn)對SQL查詢語言的封裝。也就是說,你可以不會管理數(shù)據(jù)庫,可以不會SQL語言,你同樣能通過Python的代碼進行數(shù)據(jù)庫的操作。Django通過ORM對數(shù)據(jù)庫進行操作,奉行代碼優(yōu)先的理念,將Python程序員和數(shù)據(jù)庫管理員進行分工解耦。

ORM(Object-Relational Mapping) 即對象-關系映射,從效果上看,實現(xiàn)了一個可在編程語言里直接使用的虛擬對象數(shù)據(jù)庫。這種思想在很多架構設計中都有體現(xiàn),android開發(fā)中常用的GreenDao就是一個輕量的ORM設計。

設計model(即數(shù)據(jù)庫結(jié)構)

因為Django的model機制是ORM的一種實踐,所以說,設計了model,就設計了數(shù)據(jù)庫結(jié)構。這里我們只演示一個記錄設備啟動次數(shù)的api接口所需的基本字段。

from django.db import models

class DeviceReport(models.Model):
    """
    收集設備相關的統(tǒng)計數(shù)據(jù)
    report_id
        自增id作為主鍵
    report_type
        上報類型,比如啟動上報:open
    report_time
        上報時間戳
    device_id
        可以描述設備的id
    ip_address
        公網(wǎng)ip地址   
    """
    report_id = models.IntegerField(primary_key=True)
    report_type = models.CharField(max_length=100)
    report_time = models.DateTimeField(auto_now_add=True)
    device_id = models.CharField(max_length=200)
    ip_address = models.CharField(max_length=50)

生效數(shù)據(jù)庫
在每次修改model之后,都需要進行遷移和生效動作,畢竟我們修改了數(shù)據(jù)庫結(jié)構了。

? python manage.py makemigrations rouboapi                  
Migrations for 'rouboapi':
  rouboapi/migrations/0001_initial.py
    - Create model DeviceReport

? python manage.py migrate                                  
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, rouboapi, sessions
Running migrations:
  Applying rouboapi.0001_initial... OK

執(zhí)行成功后,會生成rouboapi_devicereport的表。

實現(xiàn)序列化器

我們使用Django REST framework 提供的序列化器簡化代碼。

from rest_framework import serializers
from rouboapi.models import DeviceReport

class DeviceReportSerializer(serializers.HyperlinkedModelSerializer):
    """
    序列化上報接口數(shù)據(jù)
    """
    class Meta:
        model = DeviceReport
        fields = ('report_id', 'report_type', 'report_time', 'device_id', 'ip_address')

實現(xiàn)視圖

先使用APIView來簡化代碼,目前還沒研究清楚如果使用ViewSets實現(xiàn)單一的get接口(其他接口不能實現(xiàn)的)的方法。

from rouboapi.serializers import DeviceReportSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class DeviceReport(APIView):
    """
    上報設備信息, 無需鑒權
    """
       authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        serializer = DeviceReportSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

接口測試

瀏覽器訪問:http://127.0.0.1:8000/rouboapi/v1/report/?report_type=open&device_id=testid&ip_address=127.0.0.1 ,出現(xiàn)REST默認界面,作為接口訪問時,加入format=json參數(shù)即可。

image.png

檢查數(shù)據(jù)庫的變化:

mysql> select * from rouboapi_devicereport;
+-------------+----------------------------+-----------+------------+
| report_type | report_time                | device_id | ip_address |
+-------------+----------------------------+-----------+------------+
| open        | 2018-08-28 11:54:08.724136 | testid    | 127.0.0.1  |
| open        | 2018-08-28 11:55:06.205909 | testid    | 127.0.0.1  |
| open        | 2018-08-28 11:55:08.746301 | testid    | 127.0.0.1  |
+-------------+----------------------------+-----------+------------+

文檔化

Api接口文檔化功能是Django REST Framework提供的一大特色功能,操作也簡單。

pip install coreapi pygments markdown

安裝上面依賴包后,只要修改urls.py文件即可:

from django.conf.urls import url
from . import views
from rest_framework.documentation import include_docs_urls
API_TITLE = 'roubo api documentation'
API_DESCRIPTION = 'roubo api server for rouboinfo'

urlpatterns = [
    url(r'v1/report/$', views.DeviceReport.as_view(), name='DeviceReport'),
    url(r'docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION, authentication_classes=[], permission_classes=[]))
]

查看樣式,包含交互式的接口測試功能。


image.png

完成

GitHub - roubo/rouboApi: 基于Django REST framework 實現(xiàn)一些業(yè)務api
嗶嗶嗶。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容