1. getgit
import requests # 最簡單的get請求 r = requests.get(url) print(r.status_code) print(r.json()) # url 中?key=value&key=value r = requests.get(url, params=params) # form 表單 params = {"username":"name", "password":"passw0rd"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = requests.get(url, params=params, headers=headers) # 下載 r = requests.get(url) r.raise_for_status() with open(target, 'wb') as f: for ch in r.iter_content(10000): result_file_size += f.write(ch)
2. post請求github
data = {'name':'train', 'device':'CN0989'} r = requests.post(url, json=data) #上傳 files = { "file": (os.path.basename(filepath), open(filepath, "rb"), "application/zip") } print('POST %s'%url) with open(filepath, 'rb') as f: r = requests.post(url, files=files)
r = requests.post(url, json=json_dict, headers=headers) # 保持response流,保證接收完整 with requests.get('https://httpbin.org/get', stream=True) as r: # Do things with the response here. # 上傳文件 with open('massive-body', 'rb') as f: requests.post('http://some.url/streamed', data=f) # 上傳文件 2 指定文件格式 files = {'file': (filename, open(filename, 'rb), 'application/zip')} r = requests.post(url, files=files) print(r.status_code) print(r.json()) # 上傳多個文件 url = 'https://httpbin.org/post' multiple_files = [ ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')), ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))] r = requests.post(url, files=multiple_files) r.text
3. 登陸json
_session = requests.Session() # login url = '%s/login'%_basic_url params = {"username":"admin", "password":"admin"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = _session.post(url, params=params, headers=headers) #作其餘請求 r = _session.get(url) _session.close()
4. 使用basic登陸api
from requests.auth import HTTPBasicAuth r = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) r.encoding = 'utf-8' print r.status_code print r.text print r.json()