【PYTHON】【requests】【自定义authen,requests.auth AuthBase】

  • requests 提供的authen方式有HTTPBasicAuth,HTTPDigestAuth,OAuth等

 

 

  • 同时requests提供继承AuthBase,来自定义authen

 

  • 例如,登录时使用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:\Python27\python.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:\Python27\python.exe C:/PycharmProjects/reqTest1/src/reqUnamePass2.py
{"testUname": "pp123", "testPassword": "pppassword", "other": ""}

Process finished with exit code 0

其他使用PreparedRequest的方式

  1. 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
posted @ 2017-01-23 14:22  AlexBai326  阅读(3402)  评论(0编辑  收藏  举报