udg/ecoms/dataserver/interfaces: udg.py

File udg.py, 2.1 KB (added by sixto, 3 years ago)
Line 
1# -*- coding: utf-8 -*-
2"""
3Created on Wed Jan 22 16:26:17 2014
4
5@author: antonio
6"""
7
8#import urllib2, cookielib, urlparse, pydap, re
9#from pydap.exceptions import ClientError
10#page= 'http://meteo.unican.es/tds5/dodsC/system4/System4_Seasonal_15Members.ncml.dds'
11#parts=urlparse.urlsplit(page)
12#
13#pwdmngr = urllib2.HTTPPasswordMgrWithDefaultRealm()
14#pwdmngr.add_password(None, urlparse.urlunsplit([parts[0],parts[1],'','','']), 'cofinoa', 'felipeii')
15#authinfo = urllib2.HTTPBasicAuthHandler(pwdmngr)
16#myopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()),authinfo)
17#fp=myopener.open(page)
18#data=fp.read()
19#opened = urllib2.install_opener(myopener)
20#output = urllib2.urlopen(page)
21
22   
23def install_udg_client(username=None, password=None):
24    import urllib2, cookielib, urlparse, pydap.lib, re
25    from pydap.exceptions import ClientError
26    pwdmngr = urllib2.HTTPPasswordMgrWithDefaultRealm()
27    authinfo = urllib2.HTTPBasicAuthHandler(pwdmngr)
28    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()),authinfo)
29    opener.addheaders = [('User-agent', pydap.lib.USER_AGENT)]
30    def new_request(url):
31        scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
32        if '@' in netloc:
33            credentials, netloc = netloc.split('@', 1)  # remove credentials from netloc
34            username, password = credentials.split(':', 1)
35            pwdmngr.add_password(None, urlparse.urlunsplit([scheme,netloc,'','','']), username, password)
36        url = urlparse.urlunsplit((
37                scheme, netloc, path, query, fragment
38                )).rstrip('?&')
39        r = opener.open(url)
40        resp = r.headers.dict
41        resp['status'] = str(r.code)
42        data = r.read()
43       
44        if resp.get("content-description") in ["dods_error", "dods-error"]:
45            m = re.search('code = (?P<code>[^;]+);\s*message = "(?P<msg>.*)"',
46                    data, re.DOTALL | re.MULTILINE)
47            msg = 'Server error %(code)s: "%(msg)s"' % m.groupdict()
48            raise ClientError(msg)
49   
50        return resp, data
51    from pydap.util import http
52    http.request = new_request