安裝相關模塊
pip install requests requests-toolbelt
代碼實例
import requests
import json
from PIL import Image
from io import BytesIO
from requests_toolbelt import MultipartEncoder
'''
使用 requests 請求返回的 response 注意事項
response.text 獲得響應結果的字符串類型
response.content 獲得響應結果的bytes(二進制數據流類型,可用來處理返回的二進制文件流) 如果是圖片的話可以使用 Image.open(BytesIO(r.content)).show() 打開查看
response.status_code 獲得響應結果的狀態碼
response.headers 獲得響應結果的請求頭
response.encoding 獲得響應結果的編碼
response.url 獲得請求的url
response.json() 將獲得響應結果轉換成 json.loads(str) 後的結果,在python中得到字典類型
'''
def get_request(url, params, headers=None):
'''
發起GET請求
:url 請求的地址 字符串類型
:params 請求的參數 字典類型
:headers 定義請求頭 字典類型
'''
return requests.get(url=url, params=params, headers=headers)
def post_www_form_request(url, www_form, headers=None):
'''
發起POST請求 發送x-www-form-urlencoded請求體
:url 請求的地址 字符串類型
:www_form x-www-form-urlencoded請求體 字典類型
:headers 定義請求頭 字典類型
'''
return requests.post(url=url, data=www_form, headers=headers)
def post_form_data_request(url, form_data, headers=None):
'''
發起POST請求 發送form-data請求體
:url 請求的地址 字符串類型
:form_data form-data請求體 字典類型
:headers 定義請求頭 字典類型
'''
default_headers = {'Content-Type': 'multipart/form-data'}
if headers:
default_headers.update(headers)
m = MultipartEncoder(fields=form_data)
default_headers['Content-Type'] = m.content_type
print(default_headers)
return requests.post(url=url, data=m, headers=default_headers)
def post_json_data_request(url, json_data, headers=None):
'''
發起POST請求 發送json請求體
:url 請求的地址 字符串類型
:json_data json類型請求體 字典類型
:headers 定義請求頭 字典類型
'''
# 方式一
# default_headers = {'Content-Type': 'application/json'}
# if headers:
# default_headers.update(headers)
# return requests.post(url=url, data=json.dumps(json_data), headers=default_headers)
# 方式二
return requests.post(url=url, json=json_data, headers=headers)
def post_files_request(url, files, headers=None):
'''
發起POST請求 請求體爲文件
:url 請求的地址 字符串類型
:files 文件類型請求體 文件類型
:headers 定義請求頭 字典類型
'''
# 攜帶請求頭
default_headers = {'Authorization': 'bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxMDIxNTk5MjgwMX0.GFs_smaKQ55taYgctbDzw2ooOdKNuy-HqobHXB2nE1o'}
if headers:
default_headers.update(headers)
return requests.post(url=url, files=files, headers=default_headers)
if __name__ == '__main__':
# 測試GET請求
# print(get_request('http://127.0.0.1:9000/wechat/good/', {'page': 1, 'page_size': 2}).json())
# print(post_www_form_request('http://127.0.0.1:9000/mobilelogin/', {'mobile': '17316280277', 'code': '1234'}).json())
# (('mobile', '17316280277'), ('code', '1234'))
# print(post_form_data_request('http://127.0.0.1:9000/mobilelogin/', {'mobile': '17316280277', 'code': '1234'}).json())
# print(post_json_data_request('http://127.0.0.1:9000/mobilelogin/', {'mobile': '17316280277', 'code': '1234'}).json())
print(post_files_request('http://127.0.0.1:9000/uploadfile/', {'file': open('img1.png', 'rb'), 'file1': open('1.xls', 'rb')}).json())