Python's requests tips: pythonrequests

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.