Debian Codegraph @

mechanize/_util.py

raw symbols SCIP
1 """Utility functions and date/time routines.
2
3 Copyright 2002-2006 John J Lee <[email protected]>
4
5 This code is free software; you can redistribute it and/or modify it
6 under the terms of the BSD or ZPL 2.1 licenses (see the file
7 LICENSE included with the distribution).
8 """
9
10 from __future__ import absolute_import
11
12 import re
13 import time
14 import warnings
15 from calendar import timegm
16
17
18 class ExperimentalWarning(UserWarning):
19 pass
20
21
22 def experimental(message):
23 warnings.warn(message, ExperimentalWarning, stacklevel=3)
24
25
26 def hide_experimental_warnings():
27 warnings.filterwarnings("ignore", category=ExperimentalWarning)
28
29
30 def reset_experimental_warnings():
31 warnings.filterwarnings("default", category=ExperimentalWarning)
32
33
34 def deprecation(message):
35 warnings.warn(message, DeprecationWarning, stacklevel=3)
36
37
38 def hide_deprecations():
39 warnings.filterwarnings("ignore", category=DeprecationWarning)
40
41
42 def reset_deprecations():
43 warnings.filterwarnings("default", category=DeprecationWarning)
44
45
46 def read_file(filename):
47 with open(filename, 'rb') as f:
48 return f.read()
49
50
51 def write_file(filename, data):
52 f = open(filename, "wb")
53 try:
54 f.write(data)
55 finally:
56 f.close()
57
58
59 def get1(sequence):
60 assert len(sequence) == 1
61 return sequence[0]
62
63
64 def isstringlike(x):
65 try:
66 x + ""
67 except Exception:
68 return False
69 else:
70 return True
71
72 # Date/time conversion routines for formats used by the HTTP protocol.
73
74
75 EPOCH = 1970
76
77
78 def my_timegm(tt):
79 year, month, mday, hour, min, sec = tt[:6]
80 if ((year >= EPOCH) and (1 <= month <= 12) and (1 <= mday <= 31) and
81 (0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)):
82 return timegm(tt)
83 else:
84 return None
85
86
87 days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
88 months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
89 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
90 months_lower = []
91 for month in months:
92 months_lower.append(month.lower())
93
94
95 def time2isoz(t=None):
96 """Return a string representing time in seconds since epoch, t.
97
98 If the function is called without an argument, it will use the current
99 time.
100
101 The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
102 representing Universal Time (UTC, aka GMT). An example of this format is:
103
104 1994-11-24 08:49:37Z
105
106 """
107 if t is None:
108 t = time.time()
109 year, mon, mday, hour, min, sec = time.gmtime(t)[:6]
110 return "%04d-%02d-%02d %02d:%02d:%02dZ" % (
111 year, mon, mday, hour, min, sec)
112
113
114 def time2netscape(t=None):
115 """Return a string representing time in seconds since epoch, t.
116
117 If the function is called without an argument, it will use the current
118 time.
119
120 The format of the returned string is like this:
121
122 Wed, DD-Mon-YYYY HH:MM:SS GMT
123
124 """
125 if t is None:
126 t = time.time()
127 year, mon, mday, hour, min, sec, wday = time.gmtime(t)[:7]
128 return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % (
129 days[wday], mday, months[mon - 1], year, hour, min, sec)
130
131
132 UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None}
133
134 timezone_re = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$")
135
136
137 def offset_from_tz_string(tz):
138 offset = None
139 if tz in UTC_ZONES:
140 offset = 0
141 else:
142 m = timezone_re.search(tz)
143 if m:
144 offset = 3600 * int(m.group(2))
145 if m.group(3):
146 offset = offset + 60 * int(m.group(3))
147 if m.group(1) == '-':
148 offset = -offset
149 return offset
150
151
152 def _str2time(day, mon, yr, hr, min, sec, tz):
153 # translate month name to number
154 # month numbers start with 1 (January)
155 try:
156 mon = months_lower.index(mon.lower()) + 1
157 except ValueError:
158 # maybe it's already a number
159 try:
160 imon = int(mon)
161 except ValueError:
162 return None
163 if 1 <= imon <= 12:
164 mon = imon
165 else:
166 return None
167
168 # make sure clock elements are defined
169 if hr is None:
170 hr = 0
171 if min is None:
172 min = 0
173 if sec is None:
174 sec = 0
175
176 yr = int(yr)
177 day = int(day)
178 hr = int(hr)
179 min = int(min)
180 sec = int(sec)
181
182 if yr < 1000:
183 # find "obvious" year
184 cur_yr = time.localtime(time.time())[0]
185 m = cur_yr % 100
186 tmp = yr
187 yr = yr + cur_yr - m
188 m = m - tmp
189 if abs(m) > 50:
190 if m > 0:
191 yr = yr + 100
192 else:
193 yr = yr - 100
194
195 # convert UTC time tuple to seconds since epoch (not timezone-adjusted)
196 t = my_timegm((yr, mon, day, hr, min, sec, tz))
197
198 if t is not None:
199 # adjust time using timezone string, to get absolute time since epoch
200 if tz is None:
201 tz = "UTC"
202 tz = tz.upper()
203 offset = offset_from_tz_string(tz)
204 if offset is None:
205 return None
206 t = t - offset
207
208 return t
209
210
211 strict_re = re.compile(r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) "
212 r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$")
213 wkday_re = re.compile(
214 r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I)
215 loose_http_re = re.compile(
216 r"""^
217 (\d\d?) # day
218 (?:\s+|[-\/])
219 (\w+) # month
220 (?:\s+|[-\/])
221 (\d+) # year
222 (?:
223 (?:\s+|:) # separator before clock
224 (\d\d?):(\d\d) # hour:min
225 (?::(\d\d))? # optional seconds
226 )? # optional clock
227 \s*
228 ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone
229 \s*
230 (?:\(\w+\))? # ASCII representation of timezone in parens.
231 \s*$""", re.X)
232
233
234 def http2time(text):
235 """Returns time in seconds since epoch of time represented by a string.
236
237 Return value is an integer.
238
239 None is returned if the format of str is unrecognized, the time is outside
240 the representable range, or the timezone string is not recognized. If the
241 string contains no timezone, UTC is assumed.
242
243 The timezone in the string may be numerical (like "-0800" or "+0100") or a
244 string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the
245 timezone strings equivalent to UTC (zero offset) are known to the function.
246
247 The function loosely parses the following formats:
248
249 Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format
250 Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format
251 Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format
252 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday)
253 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday)
254 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday)
255
256 The parser ignores leading and trailing whitespace. The time may be
257 absent.
258
259 If the year is given with only 2 digits, the function will select the
260 century that makes the year closest to the current date.
261
262 """
263 # fast exit for strictly conforming string
264 m = strict_re.search(text)
265 if m:
266 g = m.groups()
267 mon = months_lower.index(g[1].lower()) + 1
268 tt = (int(g[2]), mon, int(g[0]),
269 int(g[3]), int(g[4]), float(g[5]))
270 return my_timegm(tt)
271
272 # No, we need some messy parsing...
273
274 # clean up
275 text = text.lstrip()
276 text = wkday_re.sub("", text, 1) # Useless weekday
277
278 # tz is time zone specifier string
279 day, mon, yr, hr, min, sec, tz = [None] * 7
280
281 # loose regexp parse
282 m = loose_http_re.search(text)
283 if m is not None:
284 day, mon, yr, hr, min, sec, tz = m.groups()
285 else:
286 return None # bad format
287
288 return _str2time(day, mon, yr, hr, min, sec, tz)
289
290
291 iso_re = re.compile(
292 r"""^
293 (\d{4}) # year
294 [-\/]?
295 (\d\d?) # numerical month
296 [-\/]?
297 (\d\d?) # day
298 (?:
299 (?:\s+|[-:Tt]) # separator before clock
300 (\d\d?):?(\d\d) # hour:min
301 (?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional)
302 )? # optional clock
303 \s*
304 ([-+]?\d\d?:?(:?\d\d)?
305 |Z|z)? # timezone (Z is "zero meridian", i.e. GMT)
306 \s*$""", re.X)
307
308
309 def iso2time(text):
310 """
311 As for http2time, but parses the ISO 8601 formats:
312
313 1994-02-03 14:15:29 -0100 -- ISO 8601 format
314 1994-02-03 14:15:29 -- zone is optional
315 1994-02-03 -- only date
316 1994-02-03T14:15:29 -- Use T as separator
317 19940203T141529Z -- ISO 8601 compact format
318 19940203 -- only date
319
320 """
321 # clean up
322 text = text.lstrip()
323
324 # tz is time zone specifier string
325 day, mon, yr, hr, min, sec, tz = [None] * 7
326
327 # loose regexp parse
328 m = iso_re.search(text)
329 if m is not None:
330 # XXX there's an extra bit of the timezone I'm ignoring here: is
331 # this the right thing to do?
332 yr, mon, day, hr, min, sec, tz, _ = m.groups()
333 else:
334 return None # bad format
335
336 return _str2time(day, mon, yr, hr, min, sec, tz)