和Requests相比,使用urllib3需要兩行程式碼才能夠得到HTTPResponse物件且使用HTTP Verbs是用參數的形式而非函式。
Requests
import requests
r = requests.get('https://api.github.com/events')
urllib3
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'https://api.github.com/events')
針對伺服器回傳的內容分類,分為Binary
, JSON
相較於Requests提供三種取用方式: r.content
for binary, r.text
for decoding from binary和r.json()
for json
urllib3提供一種取用方式: r.data
for binary 且json需要自行轉換
import json
http = urllib3.PoolManager()
r = http.request('GET', 'https://api.github.com/event')
json.loads(r.data.decode('utf-8'))
關於如何產生問號後面的URL query string
,Requests使用params
,urllib3需要根據不同HTTP Verbs決定實作方式
fields
Requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)
urllib3
import urllib3
from urllib.parse import urlencode
import json
http = urllib3.PoolManager()
# For GET, HEAD, and DELETE
r = http.request('GET', 'http://httpbin.org/get', fields={'key1': 'value1', 'key2': 'value2'})
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('args'))
print(r_json.get('url'))
# POST and PUT
encoded_args = urlencode({'key3': 'value3', 'key4': 'value4'})
url = 'http://httpbin.org/post?{query_string}'.format(query_string=encoded_args)
r = http.request('POST', url)
r_json = json.loads(r.data.decode('utf-8'))
print(r_json.get('args'))
print(r_json.get('url'))