『居善地』介面測試 — 3、Requests庫介紹

繁華似錦Fighting發表於2021-05-17

1、Requests庫

Requests庫是用Python語言編寫,基於urllib3模組,採用Apache2 Licensed開源協議的 HTTP 庫。

雖然Python的標準庫中urllib3模組已經包含了平常我們使用的大多數功能,但是它的 API使用起來讓人感覺不太友好。而Requests庫使用的是urllib3,因此繼承了它的所有特性,所以Requests庫比urllib3使用更加方便,可以節約我們大量的工作,完全滿足 HTTP 測試需求。

Requests庫支援HTTP 連線保持和連線池,支援使用cookie 保持會話,支援檔案上傳,支援自動確定響應內容的編碼,支援國際化的URL 和POST 資料自動編碼。現代、國際化、人性化。

Requests庫自稱 “HTTP for Humans”(讓HTTP服務於人類),說明使用更簡潔方便。

Requests庫是以 PEP 20 的箴言為中心開發的

  1. Beautiful is better than ugly.(美麗優於醜陋)
  2. Explicit is better than implicit.(直白優於含蓄)
  3. Simple is better than complex.(簡單優於複雜)
  4. Complex is better than complicated.(複雜優於繁瑣)
  5. Readability counts.(可讀性很重要)

對於 Requests 所有的貢獻都應牢記這些重要的準則。

簡而言之:Requests庫相當於Python中的“瀏覽器”,可以通過它進行網路請求、獲取網頁資料,功能強大而且特別好用。

說明PEP20

PEP20是編寫python程式的指導準則,在python shell中輸入import this就能看到是編寫python程式的指導準則,在python shell中輸入import this就能看到,內容如下:

TIM Peters的python之禪
The Zen of Python, by Tim Peters


優美勝於醜陋。
Beautiful is better than ugly.

明確勝於隱晦。
Explicit is better than implicit.

簡單勝於複雜。
Simple is better than complex.

複雜勝於難懂。
Complex is better than complicated.

扁平勝於巢狀。
Flat is better than nested.

留白勝於緊湊。
Sparse is better than dense.

可讀性很重要。
Readability counts.

特例也並不能特殊到可以違背這些原則。
Special cases aren't special enough to break the rules.

雖然實用性勝於純粹性。
Although practicality beats purity.

錯誤不應被默默地忽略。
Errors should never pass silently.

除非你明確地忽視。
Unless explicitly silenced.

面對歧義,不要嘗試去猜測。
In the face of ambiguity, refuse the temptation to guess.

應該有一種,最好是僅有一種,明顯的處理方式。
There should be one-- and preferably only one --obvious way to do it.

一開始那種方式並非顯而易見,除非你是python之父。
Although that way may not be obvious at first unless you're Dutch.

做好過不做。
Now is better than never.

不假思索就動手還不如不做。
Although never is often better than *right* now.

如果實現很難解釋,那就不是個好思路。
If the implementation is hard to explain, it's a bad idea.

如果實現易於解釋,則可能是個好思路。
If the implementation is easy to explain, it may be a good idea.

名稱空間是個絕妙的主意,我們要多多利用它。
Namespaces are one honking great idea -- let's do more of those!

2、Requests庫文件

3、Requests庫安裝

安裝Requests庫前提條件,需要安裝python環境,然後在cmd命令列中輸入python -m pip install requests(推薦)或者pip install requests即可。

如下圖:

image

執行pip list 檢視Requests庫是否安裝成功,和所安裝的版本(預設安裝最高版本。)

C:Users\ailin-L>pip list 
Package 	Version 
-------		--------
certifi 	2020.12.5
chardet 	4.0.0
idna 		2.10
pip 		19.2.3
requests 	2.25.1
selenium 	3.141.0
setuptools 	41.2.0
ur11ib3 	1.25.9

4、Requests庫的使用

(1)使用步驟

簡單介紹一下Requests庫步驟。

#1.匯入requests庫
import requests

#2.準備介面三要素
# 2.1 明確請求地址
url = "http://127.0.0.1:8000/api/departments/"
# 2.2 明確請求引數
# 2.3 傳送請求+請求方式
response = requests.get(url=url)

# 檢視返回值
print(response)


# 舉例:
# 1.匯入requests庫
import requests  

# 2.使用requests庫
# 傳送請求
response = requests.get('https://api.github.com/events')  
# 檢視結果
print(response.status_code)  
print(response.headers['content-type'])  
print(response.encoding)  
print(response.json())

(2)示例練習

"""
1.學習目標
    必須掌握requests庫的基本使用
2.操作步驟
    # 1.匯入requests庫
    # 2.明確請求地址
    # 3.明確請求引數
    # 4.傳送請求
3.需求
    使用requests庫來請求學生管理系統一查詢所有學院介面
4.總結
    返回值的獲取
    response.text  # 獲取返回值文字(將返回值以文字格式顯示)
    response.json()  # 獲取json格式的返回值,對於返回值型別為json格式比較友好
    response.status_code  # 獲取狀態碼---HTTP協議響應狀態碼
    response.headers  # 獲取響應頭
    response.content # 獲取響應原始碼(多用於爬蟲)
5.json和python轉化
    json.dumps(需要轉換的python物件,indent=2,ensure_ascii=False)
        indent  表示格式化輸出時縮排
        ensure_ascii=False 表示對非ascii字元不做轉化
"""
# 1.匯入requests庫
import requests
import json

# 2.明確請求地址
url = "http://127.0.0.1:8000/api/departments/"

# 3.明確請求引數
# 沒有引數不用寫

# 4.傳送請求
response = requests.get(url=url)
# print(response)
# 結果:<Response [200]>


# 5.獲取返回值內容
res = response.json()  # 會獲得一個字典格式的物件
print(type(res))  # <class 'dict'>

# 6.python字典轉換為json字串
# 使用json庫實現

# 將python物件轉換為json字串
result = json.dumps(res, indent=2, ensure_ascii=False)
print(type(result))  # 字串型別<class 'str'>
print(result)

# json.loads()  # 將json字串轉換為python物件


"""
結果:(簡略,有17個,只展示兩個,看看格式即可)
{
  "count": 17,
  "next": null,
  "previous": null,
  "results": [
    {
      "dep_id": "T02",
      "dep_name": "Java_2學院",
      "master_name": "Java-Master",
      "slogan": "java"
    },
    {
      "dep_id": "T03",
      "dep_name": "Java_3學院",
      "master_name": "Java-Master",
      "slogan": "java"
    }
}
"""

5、補充:Json資料和Python物件互相轉化

Python3 中可以使用 Json模組來對 JSON 資料進行編解碼,它主要提供了四個方法: dumpsdumploadsload

(1)dump方法和dumps方法說明:

dump方法和dumps方法對Python物件進行序列化,將一個Python物件進行JSON格式的編碼。

json.dumps(obj, *, 
           skipkeys=False, 
           ensure_ascii=True, 
           check_circular=True,
           allow_nan=True, 
           cls=None, 
           indent=None, 
           separators=None,
           default=None, 
           sort_keys=False, 
           **kw)

說明dumps方法中常用的幾個引數:

  • obj:表示是要序列化的物件。
  • ensure_ascii:預設值為True,用來控制生成的JSON字串的編碼,能將所有傳入的非ASCII字元轉義輸出。如果ensure_asciiFalse,保持原有編碼,則這些字元將按原樣輸出。
  • indent:可以用來控制JSON字串的換行和縮排效果,預設值為None
    如果indent是非負整數或字串,那麼JSON陣列元素和物件成員將使用該縮排級別進行輸入;
    indent為0、負數或“”僅插入換行符;
    indent使用正整數縮排多個空格;
    如果indent是一個字串(例如“\t”),則該字串用於縮排每個級別。
  • sort_keys:預設值為False,如果sort_keysTrue,則字典的輸出將按鍵值排序。

其他引數看原始碼即可,原始碼中對dumps方法中的每個引數都有詳細的說明。

(2)load方法和loads方法說明:

load方法和loads方法對Python物件進行反序列化方法,將JSON格式資料解碼為Python物件。

json.loads(s, *, 
           encoding=None, 
           cls=None, 
           object_hook=None, 
           parse_float=None,
           parse_int=None, 
           parse_constant=None, 
           object_pairs_hook=None, 
           **kw):

說明loads方法中常用的幾個引數:

  • s:將s(包含JSON文件的strbytesbytearray例項)反序列化為Python物件。
  • encoding:指定一個編碼的格式。

其他引數看原始碼即可,原始碼中對loads方法中的每個引數都有詳細的說明。

注意:如果進行反序列化(解碼)的資料不是一個有效的JSON文件,將會引發 JSONDecodeError異常。

(3)Python物件與 Json資料型別轉換:

Python物件轉Json資料:

Python JSON
dict object
list, tuple array
str string
int, float, int-&float-derived emuns number
True true
False false
None null

Json資料轉Python物件:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

相關文章