iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
0

Make a request

和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')

Response Content

針對伺服器回傳的內容分類,分為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

關於如何產生問號後面的URL query string,Requests使用params,urllib3需要根據不同HTTP Verbs決定實作方式

  • GET, HEAD, and DELETE: 使用fields
  • POST and PUT: manually encode query parameters in the URL

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'))

參考


上一篇
Day19-Requests-The User Guide-Advanced Usage-4
下一篇
Day21-urllib3-User Guide-2
系列文
Why it works: python requests and urllib330
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言