|
| 1 | +create schema http_client; |
| 2 | + |
| 3 | +do $$ |
| 4 | +begin |
| 5 | + execute 'alter database '||current_database()||' set http_client.connect_timeout = 2;'; |
| 6 | +end; |
| 7 | +$$ language plpgsql; |
| 8 | + |
| 9 | +create type http_client.response as ( |
| 10 | + url_requested text, |
| 11 | + url_received text, |
| 12 | + status_code integer, |
| 13 | + headers json, |
| 14 | + body text, |
| 15 | + is_json boolean |
| 16 | +); |
| 17 | + |
| 18 | +create or replace function http_client._get(url text, timeout integer, headers jsonb) returns http_client.response as $$ |
| 19 | +try: |
| 20 | + from urllib2 import Request, urlopen, HTTPError |
| 21 | + import json |
| 22 | + res = {} |
| 23 | + res['url_requested'] = url |
| 24 | + res['body'] = res['status_code'] = res['url_received'] = None |
| 25 | + res['is_json'] = res['headers'] = None |
| 26 | + try: |
| 27 | + req = Request(url) |
| 28 | + if headers: |
| 29 | + for k, v in json.loads(headers).iteritems(): |
| 30 | + req.add_header(k, v) |
| 31 | + conn = urlopen(req, timeout = timeout) |
| 32 | + res['body'] = conn.read() |
| 33 | + res['status_code'] = conn.getcode() |
| 34 | + res['url_received'] = conn.geturl() |
| 35 | + respHeaders = conn.info().dict |
| 36 | + res['headers'] = json.dumps(respHeaders) |
| 37 | + if 'content-type' in respHeaders and respHeaders['content-type'].find('application/json') >= 0: |
| 38 | + res['is_json'] = True |
| 39 | + #res['body_jsonb'] = json.loads(res['body']) # try/except |
| 40 | + else: |
| 41 | + res['is_json'] = False |
| 42 | + conn.close() |
| 43 | + except HTTPError as e: |
| 44 | + res['status_code'] = e.code |
| 45 | + res['headers'] = json.dumps(e.headers.dict) # undocumented http://stackoverflow.com/a/6402083/4677351 |
| 46 | + res['body'] = e.read() |
| 47 | + |
| 48 | + |
| 49 | + return res |
| 50 | +except Exception as e: |
| 51 | + msg = "Error in http_clien._get(): exception {0} occured." |
| 52 | + res = msg.format(e.__class__.__name__) |
| 53 | + return res |
| 54 | +$$ language plpython2u volatile; |
| 55 | + |
| 56 | +create or replace function http_client._post( |
| 57 | + |
| 58 | +create or replace function http_client.get(query text) returns http_client.response as $$ |
| 59 | + select http_client._get(query, current_setting('http_client.connect_timeout')::integer, null::jsonb); |
| 60 | +$$ language sql volatile; |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
0 commit comments