?最近需要對訪問第三方服務(wù)的接口做一些mock,我們訪問第三方的接口是在配置文件進行配置的,很方便替換,所以直接就打算起一個簡單的django服務(wù)
需要項目“源碼”交流學習加v: ct-xiaozhou
(非機構(gòu),行業(yè)變遷,同類好友多一個,多一些可能性,想要機構(gòu)可以推薦...)
? ? 請路過大佬不經(jīng)意的提點!謝謝
? ? 思路:
? ? ? ? 1. 找一個開源的django框架(直接其它的都不需研究了,因為測試比較少搞這些。另外其實可以找最簡單的demo,我只是順手)
? ? ? ? 2. 添加接口,并做處理
? ? ? ? 3. 接口參數(shù)寫入數(shù)據(jù)庫中, 可方便定義返回內(nèi)容
(注:我使用的是開源項目automagic 作者ray)
(注意這邊演示的前提就是找了一個對應(yīng)的基本可用的demo項目哦,之后只需要做少量編輯)
添加接口的過程:
1. 找到需要啟動的manage.py文件,找到配置文件路徑

2.找到主url的路徑

3.找到想要添加接口的子節(jié)點

4. 在對應(yīng)的urls.py文件中,添加你需要的接口?

5.接下來,來定義這個接口的返回,在對應(yīng)的views.py文件中,定義處理該接口的方法咯

6. 最后附上本次要mock的接口公共方法(“項目的源碼”請?zhí)砑觲ei v:ct-xiaozhou,行業(yè)變遷,愿多個可能性)

說明:沒有使用django的數(shù)據(jù)處理方式,直接使用mysql處理方法了
def commonDeel_99shou(request, apiname):
? ? mysqla = TestMysqlDB()
? ? apiinfo = mysqla.getOneData(f"SELECT returnStatus FROM test_work.mock_api_info where apiname='{apiname}'")
? ? apireturnMsg = mysqla.getOneData(
? ? ? ? f"SELECT returnMsg FROM test_work.mock_api_return where apiname='{apiname}' and apiStatus='{apiinfo[0]}'")
? ? mysqla.close()
? ? tempstr = apireturnMsg[0]
? ? tempstr = reStrCommonDeel(tempstr)
? ? print(type(tempstr))
? ? if request.method == 'POST':
? ? ? ? # result = {"result": 0, "msg": "執(zhí)行成功"}
? ? ? ? # return HttpResponse(json.dumps(result))
? ? ? ? try:
? ? ? ? ? ? json.loads(tempstr)
? ? ? ? except Exception as e:
? ? ? ? ? ? return JsonResponse({"result": -2, "msg": "參數(shù)格式錯誤,檢查是否json格式"})
? ? ? ? return HttpResponse(tempstr)
? ? else:
? ? ? ? return JsonResponse({"result": -1, "msg": "請求方式不對"})
?附上mysql處理(數(shù)據(jù)表是自己搭建的數(shù)據(jù)庫,使用工具界面添加的,非常簡單。。。(有sql啊,但是本人懶啊。。)):
class TestMysqlDB:
? ? test_host = '10.255.00.00'
? ? test_port = 3306
? ? test_user = 'root'
? ? test_password = '123456'
? ? test_db = 'test_work'
? ? def __init__(self, db=None):
? ? ? ? self.conn = pymysql.connect(host=self.test_host,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? port=self.test_port,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? user=self.test_user,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? password=self.test_password,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? db=self.test_db,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? charset='utf8'
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? )
? ? ? ? # 使用cursor()方法獲取操作游標
? ? ? ? self.cursor = self.conn.cursor()
? ? def getOneData(self, sqlstr):
? ? ? ? # 返回一條數(shù)據(jù)
? ? ? ? self.cursor.execute(sqlstr)
? ? ? ? return self.cursor.fetchone()
? ? def close(self):
? ? ? ? self.cursor.close()
? ? ? ? self.conn.close()