{ "testUname": "pp123", "testPassword": "pppassword", "other": "" }
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
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 scriptpython
C:\Python27\python.exe C:/PycharmProjects/reqTest1/src/reqUnamePass_backup.py 200 Process finished with exit code 0
req = Request('POST', uri, data=json.dumps(userdata)) prepped = req.prepare() print prepped.body
運行結果json
C:\Python27\python.exe C:/PycharmProjects/reqTest1/src/reqUnamePass2.py {"testUname": "pp123", "testPassword": "pppassword", "other": ""} Process finished with exit code 0
其餘使用PreparedRequest的方式post
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. Sessionthis
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