【PYTHON】【requests】【自定义authen,requests.auth AuthBase】
生活随笔
收集整理的這篇文章主要介紹了
【PYTHON】【requests】【自定义authen,requests.auth AuthBase】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
requests 提供的authen方式有HTTPBasicAuth,HTTPDigestAuth,OAuth等
http://www.python-requests.org/en/master/user/authentication/
同時requests提供繼承AuthBase,來自定義authen
http://www.python-requests.org/en/master/user/advanced/#custom-authentication
例如,登錄時使用post,使用登錄內容為json
{
"testUname": "pp123",
"testPassword": "pppassword",
"other": ""
}
自定義authen類,繼承AuthBase,將__call__中的r(PreparedRequest實例)賦值body
from requests.auth import AuthBase
class loginAuth(AuthBase):
def __init__(self, userdata):
# setup any auth-related data here
self.usdata = userdata
def __call__(self, r):
# modify and return the request
#r.headers['X-Pizza'] = self.username
r.body=self.usdata
return r
使用自定義authen
import requests
import json
from cus_authen import loginAuth
#r = requests.get('https://www.baidu.com', auth=('user', 'pass'))
userdata ={
"testUname": "pp123",
"testPassword": "pppassword",
"other": ""
}
myHeader = {"Connection": "keep-alive",
"Origin": "http://1.1.1.1",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
"Cookie": "HS.locale=zh_CN"}
http_origin = r"http://1.1.1.1"
uri = http_origin + r"/login"
rr = requests.post(uri, headers=myHeader, auth=loginAuth(json.dumps(userdata)))
print rr.status_code
now,run this script
C:Python27python.exe C:/PycharmProjects/reqTest1/src/reqUnamePass_backup.py 200 Process finished with exit code 0
def __call__(self, r)中 r是PreparedRequest的實例。構造自定義authen,主要是過r填充數據
req = Request('POST', uri, data=json.dumps(userdata))
prepped = req.prepare()
print prepped.body
運行結果
C:Python27python.exe C:/PycharmProjects/reqTest1/src/reqUnamePass2.py
{"testUname": "pp123", "testPassword": "pppassword", "other": ""}
Process finished with exit code 0
其他使用PreparedRequest的方式
Request
from requests import Request, Session
s = Session()
req = Request('GET', url, data=data, headers=header )
prepped = req.prepare()
# do something with prepped.body
# do something with prepped.headers
resp = s.send(prepped, stream=stream, verify=verify, proxies=proxies, cert=cert, timeout=timeout )
print(resp.status_code)
2. Session
from requests import Request, Session
s = Session()
req = Request('GET', url,
data=data
headers=headers
)
prepped = s.prepare_request(req)
# do something with prepped.body
# do something with prepped.headers
resp = s.send(prepped,
stream=stream,
verify=verify,
proxies=proxies,
cert=cert,
timeout=timeout
)
print(resp.status_code)
AuthBase
總結
以上是生活随笔為你收集整理的【PYTHON】【requests】【自定义authen,requests.auth AuthBase】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux(ubuntu) 查看系统设备
- 下一篇: C#的Enum——枚举