request使用

https版本告警問題,使用關閉告警,並且停止校驗

requests.packages.urllib3.disable_warnings()


url = 'https://rcmsapi.chinacache.com/device/%s';; % Devname

res = requests.get(url,verify=False)

請求方式

requests.get(‘https://github.com/timeline.json’) #GET請求

requests.post(“http://httpbin.org/post”) #POST請求

requests.put(“http://httpbin.org/put”) #PUT請求

requests.delete(“http://httpbin.org/delete”) #DELETE請求

requests.head(“http://httpbin.org/get”) #HEAD請求

requests.options(“http://httpbin.org/get”) #OPTIONS請求

帶參數請求

requests.get('http://www.dict.baidu.com/s';, params={'wd': 'python'})    #GET參數實例

requests.post('http://www.itwhy.org/wp-comments-post.php';, data={'comment': '測試POST'})    #POST參數實例

post json

r = requests.post('https://api.github.com/some/endpoint';, data=json.dumps({'some': 'data'}))

print(r.json())

定製header

data = {'some': 'data'}

headers = {'content-type': 'application/json',

           'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}

r = requests.post('https://api.github.com/some/endpoint';, data=data, headers=headers)

print(r.text)

response

r.status_code #響應狀態碼

r.raw #返回原始響應體,也就是 urllib 的 response 對象,使用 r.raw.read() 讀取

r.content #字節方式的響應體,會自動爲你解碼 gzip 和 deflate 壓縮

r.text #字符串方式的響應體,會自動根據響應頭部的字符編碼進行解碼

r.headers #以字典對象存儲服務器響應頭,但是這個字典比較特殊,字典鍵不區分大小寫,若鍵不存在則返回None

#*特殊方法*#

r.json() #Requests中內置的JSON解碼器

r.raise_for_status() #失敗請求(非200響應)拋出異常

上傳文件

url = 'http://127.0.0.1:5000/upload';

files = {'file': open('/home/lyb/sjzl.mpg', 'rb')}

#files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))}     #顯式的設置文件名

r = requests.post(url, files=files)

print(r.text)

超時與異常  timeout 僅對連接過程有效,與響應體的下載無關

requests.get('http://github.com';, timeout=0.001)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

代理

proxie = {'http' : 'http://122.193.14.102:80'}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章