Python Web request urllib2 Module simple Encapsulation Code _python

Source: Internet
Author: User
Tags auth base64 http request

A simple encapsulation of the Python Web request module URLLIB2.

Example:

Copy Code code as follows:

#!/usr/bin/python
#coding: Utf-8
Import Base64
Import Urllib
Import Urllib2
Import time

Class SendRequest:
'''
This class with to set and request the HTTP, and get the info of response.
e.g. set Authorization Type, request Tyep ...
e.g. get HTML content, state code, cookie.
SendRequest (' Http://10.75.0.103:8850/2/photos/square/type.json ',
Data= ' source=216274069 ', type= ' POST ', auth= ' base ',
User= ' zl2010 ', password= ' 111111 ')
'''
def __init__ (self, URL, data=none, type= ' get ', Auth=none, User=none, password=none, cookie = None, **header):
'''
Url:request, raise error if none
Date:data for post or get, must is dict type
Type:get, POST
Auth:option, if has the value must be ' base ' or ' cookie '
User:user for Auth
Password:password for Auth
Cookie:if Request with Cookie
Other Header info:
e.g. referer= ' www.sina.com.cn '
'''
Self.url = URL
Self.data = Data
Self.type = Type
Self.auth = Auth
Self.user = user
Self.password = password
Self.cookie = Cookie

If ' Referer ' in header:
Self.referer = Header[referer]
Else
Self.referer = None

If ' User-agent ' in header:
Self.user_agent = Header[user-agent]
Else
Self.user_agent = None

Self.setup_request ()
Self.send_request ()

def setup_request (self):
'''
Setup a request
'''
if Self.url = = None or Self.url = = ':
Raise ' The URL should not empty! '

# Set Request type
#print Self.url
#print Self.type
#print Self.data
#print Self.auth
#print Self.user
#print Self.password
if Self.type = = ' POST ':
Self. Req = Urllib2. Request (Self.url, Self.data)
elif Self.type = = ' Get ':
If Self.data = None:
Self. Req = Urllib2. Request (Self.url)
Else
Self. Req = Urllib2. Request (Self.url + '? ' + self.data)
Else
print ' The HTTP request type not support now! '

# #set Auth Type
if Self.auth = = ' base ':
if Self.user = = None or Self.password = none:
Raise ' The user or password is not given! '
Else
Auth_info = base64.encodestring (Self.user + ': ' + self.password). replace (' \ n ', ')
Auth_info = ' Basic ' + auth_info
#print Auth_info
Self. Req.add_header ("Authorization", Auth_info)
elif Self.auth = = ' Cookie ':
If Self.cookie = None:
Raise ' The cookie is not given! '
Else
Self. Req.add_header ("Cookie", Self.cookie)
Else
Pass # #add the other auth type

# #set Other Header Info
If Self.referer:
Self. Req.add_header (' Referer ', self.referer)
If self.user_agent:
Self. Req.add_header (' user-agent ', self.user_agent)


def send_request (self):
'''
Send a request
'''
# Get a Response object
Try
Self. Res = Urllib2.urlopen (self. REQ)
Self.source = self. Res.read ()
Self.goal_url = self. Res.geturl ()
Self.code = self. Res.getcode ()
Self.head_dict = self. Res.info (). Dict
Self. Res.close ()
Except Urllib2. Httperror, E:
Self.code = E.code
Print E

def get_code (self):
Return Self.code

def get_url (self):
Return Self.goal_url

def get_source (self):
Return Self.source

def get_header_info (self):
Return self.head_dict

def get_cookie (self):
If ' Set-cookie ' in self.head_dict:
Return self.head_dict[' Set-cookie ']
Else
Return None

def get_content_type (self):
If ' Content-type ' in self.head_dict:
Return self.head_dict[' Content-type ']
Else
Return None

def get_expires_time (self):
If ' Expires ' in self.head_dict:
Return self.head_dict[' expires ']
Else
Return None

def get_server_name (self):
If ' Server ' in Self.head_dict:
Return self.head_dict[' server '
Else
Return None

def __del__ (self):
Pass

__all__ = [SendRequest,]

if __name__ = = ' __main__ ':
'''
The example for using the SendRequest class
'''
Value = {' source ': ' 216274069 '}
data = Urllib.urlencode (value)
url = ' Http://10.75.0.103:8850/2/photos/square/type.json '
user = ' wz_0001 '
Password = ' 111111 '
Auth = ' base '
Type = ' POST '
T2 = Time.time ()
rs = sendrequest (' http://www.google.com ')
#rs = SendRequest (URL, data=data, Type=type, Auth=auth, User=user, Password=password)
print ' t2: ' + str (time.time ()-T2)
print '---------------get_code ()---------------'
Print Rs.get_code ()
print '---------------get_url ()---------------'
Print Rs.get_url ()
print '---------------get_source ()---------------'
Print Rs.get_source ()
print '---------------Get_cookie ()---------------'
Print Rs.get_cookie ()
rs = None

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.