How to use the requests module in Python _python

Source: Internet
Author: User
Tags auth error handling in python

This example describes how to use the requests module in Python. Share to everyone for your reference. The specific analysis is as follows:

Using Python in HTTP-related processing is an unnecessary hassle, including a URLLIB2 module that acquires comprehensive functionality at great complexity cost. Compared to the Urllib2,kenneth Reitz requests module, it is more concise to support the complete simple use case.

A simple example:

Imagine that we are trying to get resources from http://example.test/using the Getting method and view the return code, Content-type header information, and response body content. This matter is easy to achieve whether using URLLIB2 or requests.

Urllib2

>>> import urllib2 
>>> url = ' http://example.test/' 
>>> response = Urllib2.urlopen ( URL)
>>> response.getcode () 
>>> response.headers.getheader (' Content-type ') 
' text/html charset=utf-8 '
>>> response.read () 
' Hello, world! '

Requests

>>> import requests 
>>> URL = ' http://example.test/' 
>>> response = Requests.get ( URL) 
>>> response.status_code 
>>> response.headers[' content-type ']
' text/ html Charset=utf-8 '
>>> response.content 
u ' Hello, world! '

The two methods are very similar, and requests use the property name to get the corresponding property value, relative to the Urllib2 invocation method to read the property information in the response.
There are two subtle but important differences between the two:

1 Requests automatically has Unicode decoding of the return information
2 Requests automatically saves the return content, so you can read it multiple times, unlike Urllib2.urlopen (), which returns only one object that is similar to a file type that can only be read once.

2nd, it's a nasty thing to manipulate code in a python interactive environment.

An example of a complex point:

Now let's try a more complicated example: using the Get method to obtain the Http://foo.test/secret resources, this time requires basic HTTP validation. Use the above code as a template, as if we could just replace the code between Urllib2.urlopen () to Requests.get () with a request to send Username,password.

This is the Urllib2 method:

>>> import urllib2
>>> url = ' Http://example.test/secret '
>>> password_manager = Urllib2. Httppasswordmgrwithdefaultrealm ()
>>> password_manager.add_password (None, URL, ' Dan ', ' h0tdish ')
>>> Auth_handler = urllib2. Httpbasicauthhandler (Password_manager) 
>>> opener = Urllib2.build_opener (auth_handler)
>> > Urllib2.install_opener (opener)
>>> response = urllib2.urlopen (URL)
>>> Response.getcode () 
>>> response.read ()
' Welcome to the secret page! '

A simple way to instantiate 2 classes, and then build a third class, and finally loaded into the global URLLIB2 module, and finally called the Urlopen, then the two complex classes are something
Are you confused, all the URLLIB2 documents here http://docs.python.org/release/2.7/library/urllib2.html
So how did the requests solve the same problem?

Requests

>>> import requests 
>>> URL = ' Http://example.test/secret ' 
>>> response = Requests.get (url,auth= (' Dan ', ' H0tdish '))
>>> response.status_code 
>>> Response.content 

Just add a auth keyword function when calling the method
I bet you don't have to check the documents to remember.

Fault Handling error Handling

Requests's handling of errors is also very important. If you use an incorrect username and password, urllib2 can cause a urllib2. Urlerror error, however requests will return a normal response object as you would expect. Just look at the Boolean value of the Response.ok to see if the login was successful.

>>> response = Requests.get (url,auth= (' Dan ', ' Wrongpass '))
>>> Response.ok 

Some of the other features:

* Requests is as simple as the API for head, POST, put, PATCH, and Delete methods
* It can handle the multi-part upload, also support the automatic transcoding
* Better Documentation
* There's more

Requests is very good, the next time you need to use HTTP can try.

I hope this article will help you with your Python programming.

Related Article

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.