Python Test API - 003- request傳送 和Response Content接受
阿新 • • 發佈:2018-11-14
獲取伺服器返回內容:
- Response Content
import requests
r = requests.get('https://api.github.com/events')
print(r.text[0:20])
[{"id":"7843224643",
調整返回內容的編碼方式
import requests
r = requests.get('https://api.github.com/events')
print(r.encoding)
r.encoding = 'ISO-8859-1'
print(r.text[0:20])
- Binary Response Content
import requests
r = requests.get('https://www.baidu.com/img/bd_logo1.png', {'where':'super'})
print(r.status_code)
print(r.content)
上面的bytes其實是一個圖片,用PIL庫來bytes,然後顯示圖片
import requests r = requests.get('https://www.baidu.com/img/bd_logo1.png', {'where':'super'}) from PIL import Image from io import BytesIO i = Image.open(BytesIO(r.content)) i.show()
- Json Response Content
import requests
r = requests.get('https://api.github.com/events')
print(r.json())
Requests用內建的json()方法處理JSON 資料,如果沒有內容,返回204;
非JSON內容,則丟擲ValueError:No Json object could be decoded的異常。
用r.raise_for_status()或r.status_code來檢測request是否成功。
- Raw response content
加上"stream=True".
>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
如果要將raw儲存到文字檔案中,則不用r.raw,而用r.iter_content,iter_content能自動解碼gzip和deflate transfer-encoding。
import requests
import os
r = requests.get('https://api.github.com/events', stream = True)
base_dir = os.path.dirname(__file__)
file_path = base_dir + '/file_raw.txt'
print(file_path)
with open(file_path, 'wb+') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
- Customer Headers:
如果需要給request加上http headers,傳入一個headers引數,引數是字典形式的
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
- 複雜的POST Requests
傳入字典引數,對於post,用'data='接受字典引數
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
C:\Python35\python.exe D:/pyjd/djanRestPro/api/tests.py
{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"json":null,"origin":"111.175.192.105","url":"http://httpbin.org/post"}
傳入元組,也會被轉換為字典
import requests
payload = (('key1','value1'),('key1','value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
C:\Python35\python.exe D:/pyjd/djanRestPro/api/tests.py
{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"json":null,"origin":"111.175.192.105","url":"http://httpbin.org/post"}
傳入Json引數,注意這裡要用'json='接受引數
import requests
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)
- 傳入檔案
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
顯示的傳入檔案,content_type和headers
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}