author | sylvain.thenault@logilab.fr |
Thu, 30 Apr 2009 00:37:10 +0200 | |
branch | tls-sprint |
changeset 1549 | f87561822e27 |
parent 1397 | 6cbc7bc8ea6d |
child 1603 | 56217e741939 |
permissions | -rw-r--r-- |
0 | 1 |
"""Some utilities for CubicWeb server/clients. |
2 |
||
3 |
:organization: Logilab |
|
708
b4728112625f
move utils from cw.common to cw
sylvain.thenault@logilab.fr
parents:
643
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
6 |
""" |
|
7 |
__docformat__ = "restructuredtext en" |
|
8 |
||
709 | 9 |
import locale |
0 | 10 |
from md5 import md5 |
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
11 |
from calendar import monthrange |
1024
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
12 |
from datetime import datetime, timedelta, date |
1397
6cbc7bc8ea6d
rollback florent's not-proven-to-be-useful fix
sylvain.thenault@logilab.fr
parents:
1387
diff
changeset
|
13 |
from time import time |
0 | 14 |
from random import randint, seed |
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
15 |
|
1024
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
16 |
# initialize random seed from current time |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
17 |
seed() |
0 | 18 |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
19 |
try: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
20 |
strptime = datetime.strptime |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
21 |
except AttributeError: # py < 2.5 |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
22 |
from time import strptime as time_strptime |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
23 |
def strptime(value, format): |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
24 |
return datetime(*time_strptime(value, format)[:6]) |
0 | 25 |
|
1024
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
26 |
def todate(somedate): |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
27 |
"""return a date from a date (leaving unchanged) or a datetime""" |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
28 |
if isinstance(somedate, datetime): |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
29 |
return date(somedate.year, somedate.month, somedate.day) |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
30 |
assert isinstance(somedate, date) |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
31 |
return date |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
32 |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
33 |
ONEDAY = timedelta(days=1) |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
34 |
|
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
35 |
def days_in_month(date_): |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
36 |
return monthrange(date_.year, date_.month)[1] |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
37 |
|
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
38 |
def previous_month(date_): |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
39 |
return first_day(date_) - ONEDAY |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
40 |
|
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
41 |
def next_month(date_): |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
42 |
return last_day(date_) + ONEDAY |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
43 |
|
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
44 |
def first_day(date_): |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
45 |
return date(date_.year, date_.month, 1) |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
46 |
|
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
47 |
def last_day(date_): |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
48 |
return date(date_.year, date_.month, days_in_month(date_)) |
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
49 |
|
0 | 50 |
def date_range(begin, end, incr=1, include=None): |
51 |
"""yields each date between begin and end |
|
52 |
:param begin: the start date |
|
53 |
:param end: the end date |
|
54 |
:param incr: the step to use to iterate over dates. Default is |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
55 |
one day. |
0 | 56 |
:param include: None (means no exclusion) or a function taking a |
57 |
date as parameter, and returning True if the date |
|
58 |
should be included. |
|
59 |
""" |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
709
diff
changeset
|
60 |
incr = timedelta(incr, 0, 0) |
1132 | 61 |
while begin <= end: |
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
62 |
if include is None or include(begin): |
1132 | 63 |
yield begin |
64 |
begin += incr |
|
0 | 65 |
|
709 | 66 |
def ustrftime(date, fmt='%Y-%m-%d'): |
67 |
"""like strftime, but returns a unicode string instead of an encoded |
|
68 |
string which may be problematic with localized date. |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
69 |
|
709 | 70 |
encoding is guessed by locale.getpreferredencoding() |
71 |
""" |
|
72 |
# date format may depend on the locale |
|
73 |
encoding = locale.getpreferredencoding(do_setlocale=False) or 'UTF-8' |
|
1397
6cbc7bc8ea6d
rollback florent's not-proven-to-be-useful fix
sylvain.thenault@logilab.fr
parents:
1387
diff
changeset
|
74 |
return unicode(date.strftime(str(fmt)), encoding) |
709 | 75 |
|
1024
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
76 |
def make_uid(key): |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
77 |
"""forge a unique identifier""" |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
78 |
msg = str(key) + "%.10f"%time() + str(randint(0, 1000000)) |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
79 |
return md5(msg).hexdigest() |
bb96289257bf
remove unused working_hours function, new todate function since we can't compare date and datetime objects
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
80 |
|
0 | 81 |
|
82 |
def dump_class(cls, clsname): |
|
83 |
"""create copy of a class by creating an empty class inheriting |
|
84 |
from the given cls. |
|
85 |
||
86 |
Those class will be used as place holder for attribute and relation |
|
87 |
description |
|
88 |
""" |
|
89 |
# type doesn't accept unicode name |
|
90 |
# return type.__new__(type, str(clsname), (cls,), {}) |
|
91 |
# __autogenerated__ attribute is just a marker |
|
92 |
return type(str(clsname), (cls,), {'__autogenerated__': True}) |
|
93 |
||
94 |
||
95 |
def merge_dicts(dict1, dict2): |
|
96 |
"""update a copy of `dict1` with `dict2`""" |
|
97 |
dict1 = dict(dict1) |
|
98 |
dict1.update(dict2) |
|
99 |
return dict1 |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
100 |
|
0 | 101 |
|
102 |
class SizeConstrainedList(list): |
|
103 |
"""simple list that makes sure the list does not get bigger |
|
104 |
than a given size. |
|
105 |
||
106 |
when the list is full and a new element is added, the first |
|
107 |
element of the list is removed before appending the new one |
|
108 |
||
109 |
>>> l = SizeConstrainedList(2) |
|
110 |
>>> l.append(1) |
|
111 |
>>> l.append(2) |
|
112 |
>>> l |
|
113 |
[1, 2] |
|
114 |
>>> l.append(3) |
|
115 |
[2, 3] |
|
116 |
""" |
|
117 |
def __init__(self, maxsize): |
|
118 |
self.maxsize = maxsize |
|
119 |
||
120 |
def append(self, element): |
|
121 |
if len(self) == self.maxsize: |
|
122 |
del self[0] |
|
123 |
super(SizeConstrainedList, self).append(element) |
|
124 |
||
125 |
def extend(self, sequence): |
|
126 |
super(SizeConstrainedList, self).extend(sequence) |
|
127 |
keepafter = len(self) - self.maxsize |
|
128 |
if keepafter > 0: |
|
129 |
del self[:keepafter] |
|
130 |
||
131 |
__iadd__ = extend |
|
132 |
||
133 |
||
134 |
class UStringIO(list): |
|
135 |
"""a file wrapper which automatically encode unicode string to an encoding |
|
136 |
specifed in the constructor |
|
137 |
""" |
|
138 |
||
139 |
def __nonzero__(self): |
|
140 |
return True |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
141 |
|
0 | 142 |
def write(self, value): |
143 |
assert isinstance(value, unicode), u"unicode required not %s : %s"\ |
|
144 |
% (type(value).__name__, repr(value)) |
|
145 |
self.append(value) |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
146 |
|
0 | 147 |
def getvalue(self): |
148 |
return u''.join(self) |
|
149 |
||
150 |
def __repr__(self): |
|
151 |
return '<%s at %#x>' % (self.__class__.__name__, id(self)) |
|
152 |
||
153 |
||
154 |
class HTMLHead(UStringIO): |
|
155 |
"""wraps HTML header's stream |
|
156 |
||
157 |
Request objects use a HTMLHead instance to ease adding of |
|
158 |
javascripts and stylesheets |
|
159 |
""" |
|
160 |
js_unload_code = u'jQuery(window).unload(unloadPageData);' |
|
161 |
||
162 |
def __init__(self): |
|
163 |
super(HTMLHead, self).__init__() |
|
164 |
self.jsvars = [] |
|
165 |
self.jsfiles = [] |
|
166 |
self.cssfiles = [] |
|
167 |
self.ie_cssfiles = [] |
|
168 |
self.post_inlined_scripts = [] |
|
169 |
self.pagedata_unload = False |
|
170 |
||
171 |
||
172 |
def add_raw(self, rawheader): |
|
173 |
self.write(rawheader) |
|
174 |
||
175 |
def define_var(self, var, value): |
|
176 |
self.jsvars.append( (var, value) ) |
|
177 |
||
178 |
def add_post_inline_script(self, content): |
|
179 |
self.post_inlined_scripts.append(content) |
|
28
9b7067bfaa15
introduce html_headers.on_load() method as a shortcut for add_post_inline_script('''jQuery(document).ready(...''')
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
180 |
|
9b7067bfaa15
introduce html_headers.on_load() method as a shortcut for add_post_inline_script('''jQuery(document).ready(...''')
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
181 |
def add_onload(self, jscode): |
9b7067bfaa15
introduce html_headers.on_load() method as a shortcut for add_post_inline_script('''jQuery(document).ready(...''')
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
182 |
self.add_post_inline_script(u"""jQuery(document).ready(function () { |
9b7067bfaa15
introduce html_headers.on_load() method as a shortcut for add_post_inline_script('''jQuery(document).ready(...''')
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
183 |
%s |
9b7067bfaa15
introduce html_headers.on_load() method as a shortcut for add_post_inline_script('''jQuery(document).ready(...''')
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
184 |
});""" % jscode) |
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
185 |
|
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
186 |
|
0 | 187 |
def add_js(self, jsfile): |
188 |
"""adds `jsfile` to the list of javascripts used in the webpage |
|
189 |
||
190 |
This function checks if the file has already been added |
|
191 |
:param jsfile: the script's URL |
|
192 |
""" |
|
193 |
if jsfile not in self.jsfiles: |
|
194 |
self.jsfiles.append(jsfile) |
|
195 |
||
196 |
def add_css(self, cssfile, media): |
|
197 |
"""adds `cssfile` to the list of javascripts used in the webpage |
|
198 |
||
199 |
This function checks if the file has already been added |
|
200 |
:param cssfile: the stylesheet's URL |
|
201 |
""" |
|
202 |
if (cssfile, media) not in self.cssfiles: |
|
203 |
self.cssfiles.append( (cssfile, media) ) |
|
204 |
||
205 |
def add_ie_css(self, cssfile, media='all'): |
|
206 |
"""registers some IE specific CSS""" |
|
207 |
if (cssfile, media) not in self.ie_cssfiles: |
|
208 |
self.ie_cssfiles.append( (cssfile, media) ) |
|
209 |
||
210 |
def add_unload_pagedata(self): |
|
211 |
"""registers onunload callback to clean page data on server""" |
|
212 |
if not self.pagedata_unload: |
|
213 |
self.post_inlined_scripts.append(self.js_unload_code) |
|
214 |
self.pagedata_unload = True |
|
215 |
||
643
616191014b8b
[jsoncontroller] reorganize _html_exec (used by replacePageChunk) to output required css and js scripts
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
28
diff
changeset
|
216 |
def getvalue(self, skiphead=False): |
0 | 217 |
"""reimplement getvalue to provide a consistent (and somewhat browser |
218 |
optimzed cf. http://stevesouders.com/cuzillion) order in external |
|
219 |
resources declaration |
|
220 |
""" |
|
221 |
w = self.write |
|
222 |
# 1/ variable declaration if any |
|
223 |
if self.jsvars: |
|
224 |
from simplejson import dumps |
|
225 |
w(u'<script type="text/javascript">\n') |
|
226 |
for var, value in self.jsvars: |
|
227 |
w(u'%s = %s;\n' % (var, dumps(value))) |
|
228 |
w(u'</script>\n') |
|
229 |
# 2/ css files |
|
230 |
for cssfile, media in self.cssfiles: |
|
231 |
w(u'<link rel="stylesheet" type="text/css" media="%s" href="%s"/>\n' % |
|
232 |
(media, cssfile)) |
|
233 |
# 3/ ie css if necessary |
|
234 |
if self.ie_cssfiles: |
|
235 |
w(u'<!--[if lt IE 8]>\n') |
|
236 |
for cssfile, media in self.ie_cssfiles: |
|
237 |
w(u'<link rel="stylesheet" type="text/css" media="%s" href="%s"/>\n' % |
|
238 |
(media, cssfile)) |
|
239 |
w(u'<![endif]--> \n') |
|
240 |
# 4/ js files |
|
241 |
for jsfile in self.jsfiles: |
|
242 |
w(u'<script type="text/javascript" src="%s"></script>\n' % jsfile) |
|
243 |
# 5/ post inlined scripts (i.e. scripts depending on other JS files) |
|
244 |
if self.post_inlined_scripts: |
|
245 |
w(u'<script type="text/javascript">\n') |
|
246 |
w(u'\n\n'.join(self.post_inlined_scripts)) |
|
247 |
w(u'\n</script>\n') |
|
643
616191014b8b
[jsoncontroller] reorganize _html_exec (used by replacePageChunk) to output required css and js scripts
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
28
diff
changeset
|
248 |
header = super(HTMLHead, self).getvalue() |
616191014b8b
[jsoncontroller] reorganize _html_exec (used by replacePageChunk) to output required css and js scripts
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
28
diff
changeset
|
249 |
if skiphead: |
616191014b8b
[jsoncontroller] reorganize _html_exec (used by replacePageChunk) to output required css and js scripts
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
28
diff
changeset
|
250 |
return header |
616191014b8b
[jsoncontroller] reorganize _html_exec (used by replacePageChunk) to output required css and js scripts
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
28
diff
changeset
|
251 |
return u'<head>\n%s</head>\n' % header |
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
252 |
|
0 | 253 |
|
254 |
class HTMLStream(object): |
|
255 |
"""represents a HTML page. |
|
256 |
||
257 |
This is used my main templates so that HTML headers can be added |
|
258 |
at any time during the page generation. |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
259 |
|
0 | 260 |
HTMLStream uses the (U)StringIO interface to be compliant with |
261 |
existing code. |
|
262 |
""" |
|
1549
f87561822e27
some basic calendar manipulation functions, delete-trailing-whitespace
sylvain.thenault@logilab.fr
parents:
1397
diff
changeset
|
263 |
|
0 | 264 |
def __init__(self, req): |
265 |
# stream for <head> |
|
266 |
self.head = req.html_headers |
|
267 |
# main stream |
|
268 |
self.body = UStringIO() |
|
269 |
self.doctype = u'' |
|
270 |
# xmldecl and html opening tag |
|
271 |
self.xmldecl = u'<?xml version="1.0" encoding="%s"?>\n' % req.encoding |
|
272 |
self.htmltag = u'<html xmlns="http://www.w3.org/1999/xhtml" ' \ |
|
273 |
'xmlns:cubicweb="http://www.logilab.org/2008/cubicweb" ' \ |
|
274 |
'xml:lang="%s" lang="%s">' % (req.lang, req.lang) |
|
275 |
||
276 |
||
277 |
def write(self, data): |
|
278 |
"""StringIO interface: this method will be assigned to self.w |
|
279 |
""" |
|
280 |
self.body.write(data) |
|
281 |
||
282 |
def getvalue(self): |
|
283 |
"""writes HTML headers, closes </head> tag and writes HTML body""" |
|
284 |
return u'%s\n%s\n%s\n%s\n%s\n</html>' % (self.xmldecl, self.doctype, |
|
285 |
self.htmltag, |
|
286 |
self.head.getvalue(), |
|
287 |
self.body.getvalue()) |
|
288 |
||
289 |
||
290 |
class AcceptMixIn(object): |
|
291 |
"""Mixin class for vobjects defining the 'accepts' attribute describing |
|
292 |
a set of supported entity type (Any by default). |
|
293 |
""" |
|
294 |
# XXX deprecated, no more necessary |
|
295 |
||
296 |