Package restkit :: Package util
[hide private]
[frames] | no frames]

Source Code for Package restkit.util

  1  # -*- coding: utf-8 - 
  2  # 
  3  # This file is part of restkit released under the MIT license.  
  4  # See the NOTICE for more information. 
  5   
  6  import time 
  7  import urllib 
  8   
  9  from restkit.errors import InvalidUrl 
 10   
 11  weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] 
 12  monthname = [None, 
 13               'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
 14               'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 
 15                
16 -def http_date(timestamp=None):
17 """Return the current date and time formatted for a message header.""" 18 if timestamp is None: 19 timestamp = time.time() 20 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) 21 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( 22 weekdayname[wd], 23 day, monthname[month], year, 24 hh, mm, ss) 25 return s
26
27 -def parse_netloc(uri):
28 host = uri.netloc 29 port = None 30 i = host.rfind(':') 31 j = host.rfind(']') # ipv6 addresses have [...] 32 if i > j: 33 try: 34 port = int(host[i+1:]) 35 except ValueError: 36 raise InvalidUrl("nonnumeric port: '%s'" % host[i+1:]) 37 host = host[:i] 38 else: 39 # default port 40 if uri.scheme == "https": 41 port = 443 42 else: 43 port = 80 44 45 if host and host[0] == '[' and host[-1] == ']': 46 host = host[1:-1] 47 return (host, port)
48
49 -def to_bytestring(s):
50 if not isinstance(s, basestring): 51 raise TypeError("value should be a str or unicode") 52 53 if isinstance(s, unicode): 54 return s.encode('utf-8') 55 return s
56
57 -def url_quote(s, charset='utf-8', safe='/:'):
58 """URL encode a single string with a given encoding.""" 59 if isinstance(s, unicode): 60 s = s.encode(charset) 61 elif not isinstance(s, str): 62 s = str(s) 63 return urllib.quote(s, safe=safe)
64 65
66 -def url_encode(obj, charset="utf8", encode_keys=False):
67 items = [] 68 if isinstance(obj, dict): 69 for k, v in list(obj.items()): 70 items.append((k, v)) 71 else: 72 items = list(items) 73 74 tmp = [] 75 for k, v in items: 76 if encode_keys: 77 k = encode(k, charset) 78 79 if not isinstance(v, (tuple, list)): 80 v = [v] 81 82 for v1 in v: 83 if v1 is None: 84 v1 = '' 85 elif callable(v1): 86 v1 = encode(v1(), charset) 87 else: 88 v1 = encode(v1, charset) 89 tmp.append('%s=%s' % (urllib.quote(k), urllib.quote_plus(v1))) 90 return '&'.join(tmp)
91
92 -def encode(v, charset="utf8"):
93 if isinstance(v, unicode): 94 v = v.encode(charset) 95 else: 96 v = str(v) 97 return v
98 99
100 -def make_uri(base, *args, **kwargs):
101 """Assemble a uri based on a base, any number of path segments, 102 and query string parameters. 103 104 """ 105 106 # get encoding parameters 107 charset = kwargs.pop("charset", "utf-8") 108 safe = kwargs.pop("safe", "/:") 109 encode_keys = kwargs.pop("encode_keys", True) 110 111 base_trailing_slash = False 112 if base and base.endswith("/"): 113 base_trailing_slash = True 114 base = base[:-1] 115 retval = [base] 116 117 # build the path 118 _path = [] 119 trailing_slash = False 120 for s in args: 121 if s is not None and isinstance(s, basestring): 122 if len(s) > 1 and s.endswith('/'): 123 trailing_slash = True 124 else: 125 trailing_slash = False 126 _path.append(url_quote(s.strip('/'), charset, safe)) 127 128 path_str ="" 129 if _path: 130 path_str = "/".join([''] + _path) 131 if trailing_slash: 132 path_str = path_str + "/" 133 elif base_trailing_slash: 134 path_str = path_str + "/" 135 136 if path_str: 137 retval.append(path_str) 138 139 params_str = url_encode(kwargs, charset, encode_keys) 140 if params_str: 141 retval.extend(['?', params_str]) 142 143 return ''.join(retval)
144