Package ternate :: Module utils
[hide private]
[frames] | no frames]

Source Code for Module ternate.utils

  1   
  2  """ 
  3   
  4  utils.py 
  5  ======== 
  6   
  7  Misc utilities for ternate 
  8  -------------------------- 
  9   
 10  General purpose helper functions and classes for ternate 
 11   
 12  License: GPL-2 
 13   
 14  """ 
 15   
 16  #pylint: disable-msg=C0103 
 17   
 18  import urllib 
 19  import logging 
 20  import urlparse 
 21  from httplib import HTTPConnection 
 22  from urllib2 import build_opener, HTTPError, ProxyHandler, URLError 
 23   
 24   
 25  __docformat__ = 'epytext' 
 26   
 27  LOG = logging.getLogger('ternate') 
 28   
 29  COLOR = {'normal': "\033[0m", 
 30            'bold': "\033[1m", 
 31            'underline': "\033[4m", 
 32            'blink': "\033[5m", 
 33            'reverse': "\033[7m", 
 34            'black': "\033[30m", 
 35            'red': "\033[31m", 
 36            'green': "\033[32m", 
 37            'yellow': "\033[33m", 
 38            'blue': "\033[34m", 
 39            'magenta': "\033[35m", 
 40            'cyan': "\033[36m", 
 41            'white': "\033[37m"} 
 42   
 43   
44 -class NotFoundError(Exception):
45 46 '''File not found''' 47 48 #pylint: disable-msg=W0231
49 - def __init__(self, err_msg):
50 '''Initialize attributes''' 51 self.err_msg = err_msg
52
53 - def __str__(self):
54 return repr(self.err_msg)
55 56
57 -def fetch_file(url, proxy=None):
58 ''' 59 Download file by URL 60 61 @param url: URL of a file 62 @type url: string 63 64 @param proxy: URL of HTTP Proxy 65 @type proxy: string 66 67 @return: File 68 @rtype: string 69 70 ''' 71 if not url.startswith('http://') and not url.startswith('ftp://'): 72 try: 73 return open(url, 'r').read() 74 except IOError, errmsg: 75 LOG.error(errmsg) 76 return '' 77 LOG.debug('Fetching ' + url) 78 if proxy: 79 opener = build_opener(ProxyHandler({'http': proxy})) 80 else: 81 opener = build_opener() 82 opener.addheaders = [('Accept', 'application/rdf+xml'), 83 ('User-agent', 84 'Mozilla/5.0 (compatible; ternate ' + 85 'http://trac.assembla.com/ternate)')] 86 try: 87 result = opener.open(url) 88 except HTTPError, err_msg: 89 if err_msg.code == 404: 90 raise NotFoundError('Not found: %s' % url) 91 else: 92 LOG.error(err_msg) 93 return 94 except URLError, err_msg: 95 LOG.error(err_msg) 96 return 97 return result.read()
98 99 100 if __name__ == '__main__': 101 import doctest 102 doctest.testmod() 103