1 | ''' |
---|
2 | Created on 11 May 2010 |
---|
3 | |
---|
4 | @author: pjkersha |
---|
5 | ''' |
---|
6 | import urllib2 |
---|
7 | from M2Crypto import SSL, m2urllib2 |
---|
8 | from myproxy.client import MyProxyClient |
---|
9 | |
---|
10 | import logging |
---|
11 | import re |
---|
12 | import os |
---|
13 | import getpass |
---|
14 | from urlparse import urlparse |
---|
15 | import pydap.lib |
---|
16 | from pydap.exceptions import ClientError |
---|
17 | |
---|
18 | url = 'http://ndg3beta.badc.rl.ac.uk/' |
---|
19 | cert_file = os.path.expanduser('~/.globus/badc_cert.pem') |
---|
20 | |
---|
21 | testfile = 'dap/rapid/chime/co2_1pc/1day/chime_co2_1pc_daily_0060_197.oc.nc' |
---|
22 | |
---|
23 | def make_cert(): |
---|
24 | |
---|
25 | # Get a proxy certificate from the CEDA MyProxy instance |
---|
26 | mp = MyProxyClient(hostname='<CEDA MyProxy Service>', serverCNPrefix='') |
---|
27 | username = getpass.getuser() |
---|
28 | password = getpass.getpass() |
---|
29 | cert, key = mp.logon(username, password) |
---|
30 | |
---|
31 | # Save the certificate |
---|
32 | cert_fh = open(cert_file, 'w') |
---|
33 | cert_fh.write(key) |
---|
34 | cert_fh.write(cert) |
---|
35 | cert_fh.close() |
---|
36 | |
---|
37 | def init(): |
---|
38 | install_ndg_client(cert_file) |
---|
39 | import pydap.client |
---|
40 | |
---|
41 | |
---|
42 | def secure_init(certfile, keyfile=None): |
---|
43 | # keyfile assumed to be the same as certfile if it's omitted |
---|
44 | if keyfile is None: |
---|
45 | keyfile = certfile |
---|
46 | |
---|
47 | ctx = SSL.Context('sslv3') |
---|
48 | ctx.load_cert(certfile=certfile, keyfile=keyfile) |
---|
49 | |
---|
50 | #!TODO: persistant cookiejar |
---|
51 | opener = m2urllib2.build_opener(ctx, urllib2.HTTPCookieProcessor()) |
---|
52 | urllib2.install_opener(opener) |
---|
53 | |
---|
54 | |
---|
55 | def install_ndg_client(certfile, keyfile=None): |
---|
56 | # Create special opener with support for Cookies. |
---|
57 | secure_init(certfile, keyfile) |
---|
58 | |
---|
59 | def new_request(url): |
---|
60 | log = logging.getLogger('pydap') |
---|
61 | log.info('Opening %s' % url) |
---|
62 | r = urllib2.urlopen(url) |
---|
63 | |
---|
64 | resp = r.headers.dict |
---|
65 | resp['status'] = str(r.code) |
---|
66 | data = r.read() |
---|
67 | |
---|
68 | # When an error is returned, we parse the error message from the |
---|
69 | # server and return it in a ``ClientError`` exception. |
---|
70 | if resp.get("content-description") == "dods_error": |
---|
71 | m = re.search('code = (?P<code>\d+);\s*message = "(?P<msg>.*)"', |
---|
72 | data, re.DOTALL | re.MULTILINE) |
---|
73 | msg = 'Server error %(code)s: "%(msg)s"' % m.groupdict() |
---|
74 | raise ClientError(msg) |
---|
75 | |
---|
76 | return resp, data |
---|
77 | |
---|
78 | from pydap.util import http |
---|
79 | http.request = new_request |
---|
80 | |
---|
81 | def get(): |
---|
82 | return pydap.client.open_url(url + testfile) |
---|
83 | |
---|