The requests library uses: skip the verification code login through cookies, and use Session to keep cookies across requests

Take a system I usually test as an example. From the UI level, you must log in before you can perform subsequent operations. However, when I tested the interface provided by the interface document, I found that no login was required. return. The reason is that we have specially made an interface package here to manage the commonly used interfaces in a unified manner, and it is also convenient for other programs to call. So I haven't considered the problem of "keep the login (session) state" when testing the interface before. I read this question over the weekend, grabbed the request directly through fiddler (without the interface provided by the interface package), and learned how the requests library maintains a session.

1. View cookie changes before and after login

First open the login page, refresh it, fiddler will catch a request (should be the login interface), check the Raw in the Inspectorstab, you can see the details of the request header

 

Then enter the username, password, and verification code to log in, and view the request header information after logging in.

The cookies before and after login have changed.

You can also view cookies through the Chrome browser, as follows

  

You can see that the cookie value displayed in the browser is inconsistent with the cookie value in the request captured by fiddler. The browser displays all cookies, while fiddler only displays the cookie of a request (the cookie for each request will be different.) ); (I take the cookie in the browser)

If you want to skip the verification code login and keep the login state (that is, keep a session), you only need to extract the cookie after login and add it to a Session object of the requests library;

 

2. There are 2 ways to add cookies:

One is to write the cookie as a dictionary first, and then convert the dictionary to cookiejar

s = requests.Session()   #Open a session Session 
cookie_dict={ ' 49BAC005-7D5B-4231-8CEA-16939BEACD67 ' : ' cktest001 ' , # The cookie value obtained from the chrome browser
              ' JSESSIONID ' : ' F4FFF69B8C256DDA80F0C8DCB4C061C0 ' ,
              ' JSESSIONIDSSO ' : ' 9D49C76FD659448FDF5B0F294242B44A '
             }
s.cookies = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True) # Convert the cookie value to cookiejar type, and then pass it to the Session 

Note: This method will replace the original cookies

The second is to add cookies

s = requests.Session()   #Open a session Session 
jar = requests.cookies.RequestsCookieJar()    #Create a Cookie Jar object 
jar.set( ' 49BAC005-7D5B-4231-8CEA-16939BEACD67 ' , ' cktest001 ' ) #   To Cookie Add the cookie value to the Jar object 
jar.set( ' JSESSIONID ' , ' F4FFF69B8C256DDA80F0C8DCB4C061C0 ' )
jar.set('JSESSIONIDSSO','9D49C76FD659448FDF5B0F294242B44A')
s.cookies.update(jar) #Append   cookies to Session

 3. Complete business process: log in and enter a consultation

The function of the page is as follows. After submitting, there will be an extra piece of data in the database.

After passing the logged-in cookie into the session, you can call the submit interface (if the post-login cookie is not added, calling the submit interface directly will prompt that you are not logged in) # coding:utf- import requests



url = ' http://localhost.:8088/XXX/index/toIndex.do '   #Login interface 
header = { #Request     header , it is recommended to write it. If you don't write it, call the interface directly, it will prompt that you have no permission, you can directly Copy 
" Host " : " localhost.:8088 " ,
 " Connection " : " keep-alive " ,
 " Cache-Control " : " max-age=0 " ,
 " Accept " : " text/html,application/xhtml from fiddler +xml,application/xml;q=0.9,image/webp,*/*;q=0.8 ",
"Upgrade-Insecure-Requests":"1",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36",
"Referer":"http://localhost.:8088/XXX/index/toIndex.do",
"Accept-Encoding":"gzip, deflate, sdch",
"Accept-Language":"zh-CN,zh;q=0.8"
}

s = requests.Session() #Open   a session Session

# cookie_dict={'49BAC005-7D5B-4231-8CEA-16939BEACD67': 'cktest001',
#              'JSESSIONID':'F4FFF69B8C256DDA80F0C8DCB4C061C0',
#              'JSESSIONIDSSO':'9D49C76FD659448FDF5B0F294242B44A'
#              }
# s.cookies = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
# print(s.cookies)

jar = requests.cookies.RequestsCookieJar()   # 创建一个Cookie Jar对象
jar.set('49BAC005-7D5B-4231-8CEA-16939BEACD67','cktest001'
jar.set(the cookie value to the Cookie Jar object#Add)  'JSESSIONID','F4FFF69B8C256DDA80F0C8DCB4C061C0')
jar.set('JSESSIONIDSSO','9D49C76FD659448FDF5B0F294242B44A')
s.cookies.update(jar) #Append   cookies to Session

# r1 = s.get(url, headers=header, verify=False)   # use session to send login request
 print(s.cookies)
# print(r1.text) 
url2 = ' http://localhost:8088/XXX/saveConsult .do '   # Submit consultation information interface, 
header2 captured by fiddler ={
"Host":"localhost.:8088",
"Connection":"keep-alive",
"Content-Length":"89",
"Accept":"application/json, text/javascript, */*; q=0.01",
"Origin":"http://localhost.:8088",
"X-Requested-With":"XMLHttpRequest",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36",
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
"Referer":"http://localhost.:8088/XXX/toConsultEdit.do",
"Accept-Encoding":"gzip, deflate",
"Accept-Language":"zh-CN,zh;q=0.8"
}
data = {
     ' clientCode ' : 'test ' ,
     ' topic ' : 'topic_test ' ,
     ' content ' : ' Test interface ' ,
     ' resrcType ' : ' 0 '
}
r2 = s.post(url2, headers=header2, data=data, verify=False) # Use session to send and submit a consultation request  # verify=False means ignore verifying the SSL certificate 
print (r2.text) 
print(r2.status_code)

return result

The database also adds a corresponding data

Note: When calling the interface, it is best to pass in the request header information, otherwise the request will sometimes fail. If I don't add headers here, it will return 403, indicating no permission (oh, because I have no experience, so the first I didn't pass the headers once, and the result always failed. I thought it was because the login was not successful. Later, I simulated the request directly from the Composer of fiddler, and found this problem)

 

 

 Another problem is that, in fact, you only need to pass the logged-in cookies into the session, and then use this session to send and submit a consultation request, no need to send a login request (the above login is only to verify whether the login is successful)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324725995&siteId=291194637