get_contents() 將一個文件或網(wǎng)址讀入到字符串中,同PHP的get_contents方法。
get_contents() 接收六個參數(shù),第一個為文件路徑或網(wǎng)址,第二個為打開方式, 第三個為 請求頭:{"Accept-Encoding": "", "": ""} Accept-Encoding 為空不壓縮,壓縮時部分站點會亂碼。
第四個為請求數(shù)據(jù): {"name": "zh-CN"},第五個字符編碼,為空時自動不轉(zhuǎn)換。第六個參數(shù)為請求方式
以下是 get_contents() 的語法:
get_contents(url, mode='rb', header={}, data=None, charset="utf-8", method="GET")
● url[str]:文件路徑或網(wǎng)址。
● mode [str]:打開方式。w:寫、wb:二進制寫、r:讀、rb:二進制讀。
● header: [dict] 請求頭。
● data: [dict] 請求數(shù)據(jù)。
● charset: [str] 字符編碼,為空時自動不轉(zhuǎn)換。
● method: [str] 請求方法,GET 或 POST。
返回字符串類型。
以下展示了使用 get_contents() 的實例:
# kgcms.json的文件內(nèi)容:{'name': 'kgcms', 'www': 'http://m.bfraz.cn'}
from kyger.utility import get_contents print(get_contents('./static/0000/kgcms.json')) # 讀取文件 print(get_contents('http://m.bfraz.cn/api?action=get_web_info')) # 讀取網(wǎng)頁
以上實例運行后輸出的結(jié)果為:
'{"name": "kgcms", "www": "http://m.bfraz.cn"}' '{"name": "kgcms", "www": "http://m.bfraz.cn"}'