Django 自動生成api接口文檔教程
最近在寫測試平臺,需要實現(xiàn)一個節(jié)點服務(wù)器的api,正好在用django,準(zhǔn)備使用djangorestframework插件實現(xiàn)。
需求
實現(xiàn)一個接口,在調(diào)用時,通過傳遞的參數(shù),直接運(yùn)行對應(yīng)項目的自動化測試
環(huán)境
Python3.6 ,PyCharm,W7
項目結(jié)構(gòu)

功能實現(xiàn)
流程

我們要做的就是實現(xiàn)以上流程
安裝
pip install djangorestframework pip install markdown pip install django-filter # Filtering support
配置
INSTALLED_APPS = ( ... 'rest_framework', )
編寫代碼(本次代碼不涉及數(shù)據(jù)庫操作,只簡單的寫一個api)
①:打開AutoApi/Api/views.py 編寫如下代碼
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework import status
@csrf_exempt
def run_job(request):
# 判斷請求頭是否為json
if request.content_type != 'application/json':
# 如果不是的話,返回405
return HttpResponse('only support json data', status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)
# 判斷是否為post 請求
if request.method == 'POST':
try:
# 解析請求的json格式入?yún)?
data = JSONParser().parse(request)
except Exception as why:
print(why.args)
else:
content = {'msg': 'SUCCESS'}
print(data)
# 返回自定義請求內(nèi)容content,200狀態(tài)碼
return JsonResponse(data=content, status=status.HTTP_200_OK)
# 如果不是post 請求返回不支持的請求方法
return HttpResponseNotAllowed(permitted_methods=['POST'])
②:打開AutoApi/Api/urls.py 編寫如下代碼
from django.conf.urls import url from Api import views urlpatterns = [ url(r'^runJob/$',views.run_job), ]
③:打開AutoApi/AutoApi/urls.py 修改如下代碼
ALLOWED_HOSTS = '*' # 修改為* 代碼允許任意host
from django.conf.urls import url,include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('Api.urls')),# 新增
]
④:啟動服務(wù)
python manage.py runserver 0.0.0.0:8080

⑤:我們請求試試看

以上就是簡單的實現(xiàn)一個api ,其實開發(fā)說的接口就這么簡單,沒有那么神秘!
接下來把post 的數(shù)據(jù)env ,project,cases 解析出來傳給對應(yīng)的自動化測試入口函數(shù),就可以實現(xiàn)通過接口請求,啟動自動化測試的目的。
后續(xù)
實現(xiàn)接口調(diào)用自動化測試項目
實現(xiàn)異步接口
實現(xiàn)定時任務(wù)
這篇Django 自動生成api接口文檔教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Python開發(fā)語言中的基本數(shù)據(jù)類型
數(shù)據(jù)類型想必大家都知道是什么含義,指的是輸入數(shù)據(jù)的類型,任何數(shù)據(jù)都有明確的數(shù)據(jù)類型。本文主要和大家聊聊Python的三種基本數(shù)據(jù)類型,感興趣的可以了解一下2022-10-10
Python進(jìn)階之遞歸函數(shù)的用法及其示例
本篇文章主要介紹了Python進(jìn)階之遞歸函數(shù)的用法及其示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
python time模塊時間戳 與 結(jié)構(gòu)化時間詳解
這篇文章主要介紹了python time模塊 時間戳 與 結(jié)構(gòu)化時間的相關(guān)知識,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
python使用os.listdir和os.walk獲得文件的路徑的方法
本篇文章主要介紹了python使用os.listdir和os.walk獲得文件的路徑的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12

