Python's requests tips: pythonrequests
For Python requests, some tips are summarized and recorded.
1: Keep Cookies between requests. We can do this.
2: headers will be added to the request, which is generally written as follows:
The only inconvenience is that the subsequent code needs to be written so that the code looks bloated, so we can do this:
3: The default requests request will not be retried after the request fails, but we will inevitably encounter some network or external reasons when running the case. We can append the HTTPAdapaters parameter to the Session instance, increase the number of failed retries.
In this way, if the subsequent request fails, retry three times.
4: Redirection
Redirection may occur in network requests. We need to process a request at a time to disable redirection.
5: When a post request submits data in json format, the python object must be converted to a json object first. It may be written like this in many cases:
In fact, post has a default parameter json, which can be abbreviated:
6: Write the Interface request. When debugging, you need to check the detailed information of the Code request. Of course, you can use fiddler to view the details. In fact, you can also obtain the debug information in the code.*
7: Use grequests to Implement Asynchronous requests.
Pip install grequests
8: Send custom cookies
We use Session instances to maintain cookies between requests, but in some special cases, we need to use custom cookies.
We can do this.
9: When we need to determine the frontend and backend parallel design, there is no way to call the interface during the test. How can we perform the interface test? We can use mock or httpretty
For more information, see API_DOC.
10: count the time spent on an API request. You can use the following method:
11: Set Request timeout
These are tips about Python and requests.