source: TI12-security/trunk/python/Tests/urllib2secure_request/test_urllib2request.py @ 5350

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/Tests/urllib2secure_request/test_urllib2request.py@5350
Revision 5350, 1.9 KB checked in by pjkersha, 13 years ago (diff)

Demonstration code to try out urllib2 call to NDG Security secured URI. Use case from DOm's COWS client code that requires this type of request from a Pylons controller. Code shows how to deal with 401 and 403 responses from security middleware.

Line 
1#/usr/bin/env python
2"""Test urllib2 client with NDG Security error handling
3
4NERC DataGrid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "29/05/09"
8__copyright__ = "(C) 2009 Science and Technology Facilities Council"
9__license__ = "BSD - see LICENSE file in top-level directory"
10__contact__ = "Philip.Kershaw@stfc.ac.uk"
11__revision__ = '$Id$'
12import logging
13logging.basicConfig(level=logging.DEBUG)
14log = logging.getLogger(__name__)
15
16import urllib2
17
18def makeRequest(endpoint):
19    try:
20        req = urllib2.Request(endpoint)
21        handle = urllib2.urlopen(req)
22       
23    except urllib2.HTTPError, e:
24        if e.code == 401:
25            # Force ndg.security authentication to be triggered for the user to
26            # sign in.  Once included within a Pylons controller, uncomment the
27            # abort call to activate and remove the pass statement
28            log.debug("Code = %d" % e.code)
29            log.debug("Headers:\n\n %s" % e.headers)
30            log.debug("Response:\n\n %s" % e.read())
31            #abort(401)
32            pass
33
34        elif e.code == 403:
35            # User is authenticated but doesn't have the required permissions
36            # or an error occurred in the authorization process
37            # Read response
38            response = e.read()
39           
40            # Send response to user
41            start_response("%d %s" % (e.code, e.msg), e.headers.dict.items())
42            return response
43                           
44        else:
45            # Other error handling  - just calling raise here would probably
46            # trigger a '500 Internal Error'
47            raise
48
49if __name__ == "__main__":
50    endpoint = 'http://ndg3beta.badc.rl.ac.uk/cows/famous_control_month/wms?REQUEST=GetContext'
51    # Send via tcpmon ...
52    #endpoint = 'http://localhost:6000/cows/famous_control_month/wms?REQUEST=GetContext'
53    response = makeRequest(endpoint)
Note: See TracBrowser for help on using the repository browser.