1
2
3
4
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
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
28 host = uri.netloc
29 port = None
30 i = host.rfind(':')
31 j = host.rfind(']')
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
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
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
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
93 if isinstance(v, unicode):
94 v = v.encode(charset)
95 else:
96 v = str(v)
97 return v
98
99
101 """Assemble a uri based on a base, any number of path segments,
102 and query string parameters.
103
104 """
105
106
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
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
145
147 idx = -1
148 for i, (k, v) in enumerate(headers):
149 if k.upper() == name.upper():
150 idx = i
151 break
152 if idx >= 0:
153 headers[i] = (name.title(), value)
154 else:
155 headers.append((name.title(), value))
156 return headers
157
159 hdrs = {}
160 for (k, v) in new_headers:
161 hdrs[k.upper()] = v
162
163 found = []
164 for i, (k, v) in enumerate(headers):
165 ku = k.upper()
166 if ku in hdrs:
167 headers[i] = (k.title(), hdrs[ku])
168 found.append(ku)
169 if len(found) == len(new_headers):
170 return
171
172 for k, v in new_headers.items():
173 if k not in found:
174 headers.append((k.title(), v))
175 return headers
176