1. 程式人生 > >【python接口自動化-requests庫】【三】優化重構requests方法

【python接口自動化-requests庫】【三】優化重構requests方法

函數 pre 說明 數據 div src native 數值 我們

一、重構post請求方法

  上一張講了如何使用requests庫發送post請求,但是有時候,我們寫腳本,不可能這麽簡單,代碼完全不可復用,重復工作,那我們是不是可以想象,把我們的get,post請求,分別分裝起來呢,等我們要使用的時候就直接調用好了。

  廢話不說,直接實例。

二、實例

1.我們先抓取一個接口,這邊我直接抓了一個app接口,使用charles抓包。就用它了。如何抓包略。

技術分享圖片

2.代碼實例

定義一個發送post的函數,傳url,data參數, 返回 結果,最後調用這個函數

def send_post(url,data):

    response = requests.post(url=url,data=data)

    
return response.text

send_post(api_url,data)

3.完整的代碼,ps:api自己抓的

# coding:utf-8

import requests

test_url = "http://app.imolly.top/chaohuasuan/appNative/resource/systemConfig"

data = {
    "channel":"2",
    "imei":"352100070950797",
    "os":"1",
    "version":"1.0"
}

def send_post(url,data):

    response 
= requests.post(url=url,data=data) return response.text print send_post(test_url,data)

結果->

技術分享圖片

三、格式化json

我們得到的json數值的時候,發現是一長串,跟我們實際看到的json格式好像不一樣,那麽如何格式化呢?

首先我們要引入json庫,把返回的數據先得到json,然後使用dumps方法,這個方法比較重要的是indent,indent=2 說明每行空兩格

import json
def send_post(url,data):

response = requests.post(url=url,data=data).json()

return json.dumps(response,indent=2)

技術分享圖片

結果->

技術分享圖片

【python接口自動化-requests庫】【三】優化重構requests方法