1. Pre-configured
Importrequestsss=requests. Session () ss.headers.update ({'user-agent':'mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) gecko/20100101 firefox/54.0'})#C:\Program files\anaconda2\lib\site-packages\urllib3\connectionpool.py:858:insecurerequestwarning:#unverified HTTPS request is being made. Adding Certificate verification is strongly advised. See:ht#tps://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warningsSs.verify =False fromUrllib3.exceptionsImportinsecurerequestwarning fromWarningsImportFilterwarningsfilterwarnings ('Ignore', category =insecurerequestwarning)#http://docs.python-requests.org/zh_CN/latest/api.htmlImportLoggingTry: fromHttp.clientImporthttpconnectionexceptImporterror: fromHttplibImportHttpconnectionhttpconnection.debuglevel= 0#off 0 Open 1logging.basicconfig () Logging.getlogger (). SetLevel (Logging. DEBUG) Requests_log= Logging.getlogger ("REQUESTS.PACKAGES.URLLIB3") Requests_log.setlevel (logging. DEBUG) Requests_log.propagate=TruedefS_hooks (R, *args, * *Kwargs):Print('#'*20) Print(R.url, R.request.method, R.status_code, R.reason)Print('request Content-type: {} body: {}'. Format (R.request.headers.get ('Content-type'), r.request.body))Print('response Content-type: {} body length: {}'. Format (R.headers.get ('Content-type'), Len (r.content )))if 'JSON' inchR.headers.get ('Content-type',"'). Lower ():Print(r.content)Print('#'*20) Ss.hooks= Dict (response=s_hooks)defHttpbin (postfix="'): return 'http://httpbin.org/'+postfix#r = ss.post (Httpbin (' post '), Json=dict (' (' A ', 1), (' B ', 2)]))View Code
2.content-type
Sending JSON in Requests
ImportRequests fromPprintImportPPRINTSS=requests. Session () ss.headers['Content-type'] ='Application/myjson'R= Ss.post ('Https://httpbin.org/post', json={'my':'JSON'}, headers={'Content-type':'Somejson'}) Pprint (R.json () )View Code
Priority from high to Low: Parameter headers={' content-type ': ' Somejson '} >>> ss.headers >>> parameter json= auto-generated u ' content-type ': U ' A Pplication/json '
3. Using Retries in Requests
Retries in Requests
(1) Simple rough
S.mount ('https://', Httpadapter (max_retries=5))
(2) Finer grain size
from requests.packages.urllib3.util import Retry from requests.adapters import Httpadapter from requests import Sessions = Session () S.mount ( " https://pypi.python.org/ " =retry (total=5, status_forcelist=[500, 503 = S.get ( " https:// pypi.python.org/simple/requests/ ")
View Code
Python's requests mess