︙ | | |
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
+
+
|
'BEAUTIFY',
'BODY',
'BR',
'BUTTON',
'CENTER',
'CAT',
'CODE',
'COL',
'COLGROUP',
'DIV',
'EM',
'EMBED',
'FIELDSET',
'FORM',
'H1',
'H2',
|
︙ | | |
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
|
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
-
-
+
+
+
|
def URL(
a=None,
c=None,
f=None,
r=None,
args=[],
vars={},
args=None,
vars=None,
anchor='',
extension=None,
env=None,
hmac_key=None,
hash_vars=True,
salt=None,
user_signature=None,
scheme=None,
host=None,
port=None,
encode_embedded_slash=False,
):
"""
generate a URL
example::
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
|
︙ | | |
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
|
-
+
+
+
+
+
+
+
|
'/a/c/f/x/y/z?p=3&p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', anchor='1+2'))
'/a/c/f#1%2B2'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1', hmac_key='key'))
'/a/c/f/x/y/z?p=1&p=3&q=2&_signature=5d06bb8a4a6093dd325da2ee591c35c61afbd3c6#1'
'/a/c/f/x/y/z?p=1&p=3&q=2&_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f#1'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z']))
'/a/c/f/w/x/y/z'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z'], encode_embedded_slash=True))
'/a/c/f/w%2Fx/y%2Fz'
generates a url '/a/c/f' corresponding to application a, controller c
and function f. If r=request is passed, a, c, f are set, respectively,
to r.application, r.controller, r.function.
The more typical usage is:
|
︙ | | |
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
|
+
+
+
+
+
-
+
+
+
+
|
function2 = '%s.%s' % (function,extension or 'html')
if not (application and controller and function):
raise SyntaxError, 'not enough information to build the url'
if not isinstance(args, (list, tuple)):
args = [args]
if args:
if encode_embedded_slash:
other = '/' + '/'.join([urllib.quote(str(x), '') for x in args])
else:
other = args and urllib.quote('/' + '/'.join([str(x) for x in args])) or ''
other = args and urllib.quote('/' + '/'.join([str(x) for x in args]))
else:
other = ''
if other.endswith('/'):
other += '/' # add trailing slash to make last trailing empty arg explicit
if vars.has_key('_signature'): vars.pop('_signature')
list_vars = []
for (key, vals) in sorted(vars.items()):
if not isinstance(vals, (list, tuple)):
|
︙ | | |
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
|
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
|
-
+
|
if hash_vars and not isinstance(hash_vars, (list, tuple)):
hash_vars = [hash_vars]
h_vars = [(k, v) for (k, v) in list_vars if k in hash_vars]
# re-assembling the same way during hash authentication
message = h_args + '?' + urllib.urlencode(sorted(h_vars))
sig = hmac_hash(message,hmac_key,salt=salt)
sig = hmac_hash(message, hmac_key, digest_alg='sha1', salt=salt)
# add the signature into vars
list_vars.append(('_signature', sig))
if list_vars:
other += '?%s' % urllib.urlencode(list_vars)
if anchor:
other += '#' + urllib.quote(str(anchor))
|
︙ | | |
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
|
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
-
-
+
+
|
do not call directly. Use instead:
URL.verify(hmac_key='...')
the key has to match the one used to generate the URL.
>>> r = Storage()
>>> gv = Storage(p=(1,3),q=2,_signature='5d06bb8a4a6093dd325da2ee591c35c61afbd3c6')
>>> r.update(dict(application='a', controller='c', function='f'))
>>> gv = Storage(p=(1,3),q=2,_signature='a32530f0d0caa80964bb92aad2bedf8a4486a31f')
>>> r.update(dict(application='a', controller='c', function='f', extension='html'))
>>> r['args'] = ['x', 'y', 'z']
>>> r['get_vars'] = gv
>>> verifyURL(r, 'key')
True
>>> verifyURL(r, 'kay')
False
>>> r.get_vars.p = (3, 1)
|
︙ | | |
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
|
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
|
-
+
|
except:
# user has removed one of our vars! Immediate fail
return False
# build the full message string with both args & vars
message = h_args + '?' + urllib.urlencode(sorted(h_vars))
# hash with the hmac_key provided
sig = hmac_hash(message,str(hmac_key),salt=salt)
sig = hmac_hash(message, str(hmac_key), digest_alg='sha1', salt=salt)
# put _signature back in get_vars just in case a second call to URL.verify is performed
# (otherwise it'll immediately return false)
request.get_vars['_signature'] = original_sig
# return whether or not the signature in the request matched the one we just generated
# (I.E. was the message the same as the one we originally signed)
|
︙ | | |
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
|
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
|
-
+
|
kargs['first_only'] = True
sibs = self.siblings(*args, **kargs)
if not sibs:
return None
return sibs[0]
class CAT(DIV):
tag = ''
def TAG_unpickler(data):
return cPickle.loads(data)
def TAG_pickler(data):
d = DIV()
|
︙ | | |
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
|
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
|
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
-
+
|
class A(DIV):
tag = 'a'
def xml(self):
if self['delete']:
d = "jQuery(this).closest('%s').remove();" % self['delete']
else:
d = ''
if self['component']:
self['_onclick']="web2py_component('%s','%s');%sreturn false;" % \
(self['component'],self['target'] or '',d)
self['_href'] = self['_href'] or '#null'
if self['callback']:
self['_onclick']="ajax('%s',[],'%s');return false;" % \
(self['callback'],self['target'] or '')
elif self['callback']:
if d:
self['_onclick']="if(confirm(w2p_ajax_confirm_message||'Are you sure you want o delete this object?')){ajax('%s',[],'%s');%s};return false;" % (self['callback'],self['target'] or '',d)
else:
self['_onclick']="ajax('%s',[],'%s');%sreturn false;" % \
(self['callback'],self['target'] or '',d)
self['_href'] = self['_href'] or '#null'
elif self['cid']:
self['_onclick']='web2py_component("%s","%s");return false;' % \
(self['_href'],self['cid'])
return DIV.xml(self)
class BUTTON(DIV):
tag = 'button'
class EM(DIV):
tag = 'em'
|
︙ | | |
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
|
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
|
-
+
-
+
-
+
-
+
-
-
+
+
-
+
|
self['value'] = self['_value'] == value
requires = self['requires']
if requires:
if not isinstance(requires, (list, tuple)):
requires = [requires]
for validator in requires:
(value, errors) = validator(value)
if errors != None:
if not errors is None:
self.vars[name] = value
self.errors[name] = errors
break
if not name in self.errors:
self.vars[name] = value
return True
return False
def _postprocessing(self):
t = self['_type']
if not t:
t = self['_type'] = 'text'
t = t.lower()
value = self['value']
if self['_value'] == None:
if self['_value'] is None:
_value = None
else:
_value = str(self['_value'])
if t == 'checkbox':
if t == 'checkbox' and not '_checked' in self.attributes:
if not _value:
_value = self['_value'] = 'on'
if not value:
value = []
elif value is True:
value = [_value]
elif not isinstance(value,(list,tuple)):
value = str(value).split('|')
self['_checked'] = _value in value and 'checked' or None
elif t == 'radio':
elif t == 'radio' and not '_checked' in self.attributes:
if str(value) == str(_value):
self['_checked'] = 'checked'
else:
self['_checked'] = None
elif t == 'text' or t == 'hidden':
if value != None:
self['_value'] = value
if value is None:
self['value'] = _value
else:
self['value'] = _value
self['_value'] = value
def xml(self):
name = self.attributes.get('_name', None)
if name and hasattr(self, 'errors') \
and self.errors.get(name, None) \
and self['hideerror'] != True:
return DIV.xml(self) + DIV(self.errors[name], _class='error',
|
︙ | | |
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
|
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
|
-
+
|
tag = 'textarea'
def _postprocessing(self):
if not '_rows' in self.attributes:
self['_rows'] = 10
if not '_cols' in self.attributes:
self['_cols'] = 40
if self['value'] != None:
if not self['value'] is None:
self.components = [self['value']]
elif self.components:
self['value'] = self.components[0]
class OPTION(DIV):
|
︙ | | |
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
|
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
|
-
+
|
if isinstance(c, OPTGROUP):
component_list.append(c.components)
else:
component_list.append([c])
options = itertools.chain(*component_list)
value = self['value']
if value != None:
if not value is None:
if not self['_multiple']:
for c in options: # my patch
if value and str(c['_value'])==str(value):
c['_selected'] = 'selected'
else:
c['_selected'] = None
else:
|
︙ | | |
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
|
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
|
+
-
+
+
+
+
+
-
-
+
+
-
+
|
tag = 'form'
def __init__(self, *components, **attributes):
DIV.__init__(self, *components, **attributes)
self.vars = Storage()
self.errors = Storage()
self.latest = Storage()
self.accepted = None # none for not submitted
def accepts(
self,
vars,
request_vars,
session=None,
formname='default',
keepvalues=False,
onvalidation=None,
hideerror=False,
**kwargs
):
"""
kwargs is not used but allows to specify the same interface for FROM and SQLFORM
"""
if vars.__class__.__name__ == 'Request':
vars=vars.post_vars
if request_vars.__class__.__name__ == 'Request':
request_vars=request_vars.post_vars
self.errors.clear()
self.request_vars = Storage()
self.request_vars.update(vars)
self.request_vars.update(request_vars)
self.session = session
self.formname = formname
self.keepvalues = keepvalues
# if this tag is a form and we are in accepting mode (status=True)
# check formname and formkey
|
︙ | | |
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
|
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
|
-
+
-
+
+
|
status = self._traverse(status,hideerror)
if onvalidation:
if isinstance(onvalidation, dict):
onsuccess = onvalidation.get('onsuccess', None)
onfailure = onvalidation.get('onfailure', None)
if onsuccess and status:
onsuccess(self)
if onfailure and vars and not status:
if onfailure and request_vars and not status:
onfailure(self)
status = len(self.errors) == 0
elif status:
if isinstance(onvalidation, (list, tuple)):
[f(self) for f in onvalidation]
else:
onvalidation(self)
if self.errors:
status = False
if session != None:
if not session is None:
if hasattr(self,'record_hash'):
formkey = self.record_hash
else:
formkey = web2py_uuid()
self.formkey = session['_formkey[%s]' % formname] = formkey
if status and not keepvalues:
self._traverse(False,hideerror)
self.accepted = status
return status
def _postprocessing(self):
if not '_action' in self.attributes:
self['_action'] = ''
if not '_method' in self.attributes:
self['_method'] = 'post'
|
︙ | | |
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
|
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
|
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
-
+
+
+
+
+
+
+
+
-
+
|
def xml(self):
newform = FORM(*self.components, **self.attributes)
hidden_fields = self.hidden_fields()
if hidden_fields.components:
newform.append(hidden_fields)
return DIV.xml(newform)
def validate(self,
def validate(self,**kwargs):
values=None,
session=None,
formname='default',
keepvalues=False,
onvalidation=None,
hideerror=False,
onsuccess='flash',
onfailure='flash',
message_onsuccess=None,
message_onfailure=None,
):
"""
This function validates the form,
This function validates the form,
you can use it instead of directly form.accepts.
Usage:
In controller
def action():
form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY()))
form.validate() #you can pass some args here - see below
return dict(form=form)
This can receive a bunch of arguments
This can receive a bunch of arguments
onsuccess = 'flash' - will show message_onsuccess in response.flash
None - will do nothing
can be a function (lambda form: pass)
onfailure = 'flash' - will show message_onfailure in response.flash
None - will do nothing
can be a function (lambda form: pass)
values = values to test the validation - dictionary, response.vars, session or other - Default to (request.vars, session)
message_onsuccess
message_onfailure
next = where to redirect in case of success
any other kwargs will be passed for form.accepts(...)
"""
from gluon import current
from gluon import current, redirect
if not session: session = current.session
if not values: values = current.request.post_vars
message_onsuccess = message_onsuccess or current.T("Success!")
message_onfailure = message_onfailure or \
current.T("Errors in form, please check it out.")
kwargs['request_vars'] = kwargs.get('request_vars',current.request.post_vars)
kwargs['session'] = kwargs.get('session',current.session)
kwargs['dbio'] = kwargs.get('dbio',False) # necessary for SQLHTML forms
onsuccess = kwargs.get('onsuccess','flash')
onfailure = kwargs.get('onfailure','flash')
message_onsuccess = kwargs.get('message_onsuccess',
current.T("Success!"))
message_onfailure = kwargs.get('message_onfailure',
current.T("Errors in form, please check it out."))
next = kwargs.get('next',None)
for key in ('message_onsuccess','message_onfailure','onsuccess',
'onfailure','next'):
if key in kwargs:
del kwargs[key]
if self.accepts(values, session):
if self.accepts(**kwargs):
if onsuccess == 'flash':
if next:
current.session.flash = message_onsuccess
else:
current.response.flash = message_onsuccess
current.response.flash = message_onsuccess
elif callable(onsuccess):
onsuccess(self)
if next:
if self.vars.id:
next = next.replace('[id]',str(self.vars.id))
next = next % self.vars
if not next.startswith('/'):
next = URL(next)
redirect(next)
return True
elif self.errors:
if onfailure == 'flash':
current.response.flash = message_onfailure
elif callable(onfailure):
onfailure(self)
return False
def process(self, values=None, session=None, **args):
def process(self, **kwargs):
"""
Perform the .validate() method but returns the form
Usage in controllers:
# directly on return
def action():
#some code here
|
︙ | | |
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
|
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
|
-
-
+
+
+
|
def my_callback(status, msg):
response.flash = "Success! "+msg if status else "Errors occured"
# after argument can be 'flash' to response.flash messages
# or a function name to use as callback or None to do nothing.
def action():
return dict(form=SQLFORM(db.table).process(onsuccess=my_callback)
"""
self.validate(values=values, session=session, **args)
"""
kwargs['dbio'] = kwargs.get('dbio',True) # necessary for SQLHTML forms
self.validate(**kwargs)
return self
class BEAUTIFY(DIV):
"""
example::
|
︙ | | |
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
|
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
|
-
+
+
-
+
+
|
try:
parent_tagname=self.parent.tag
self.parent = self.parent.parent
except:
raise RuntimeError, "unable to balance tag %s" % tagname
if parent_tagname[:len(tagname)]==tagname: break
def markdown_serializer(text,tag=None,attr={}):
def markdown_serializer(text,tag=None,attr=None):
attr = attr or {}
if tag is None: return re.sub('\s+',' ',text)
if tag=='br': return '\n\n'
if tag=='h1': return '#'+text+'\n\n'
if tag=='h2': return '#'*2+text+'\n\n'
if tag=='h3': return '#'*3+text+'\n\n'
if tag=='h4': return '#'*4+text+'\n\n'
if tag=='p': return text+'\n\n'
if tag=='b' or tag=='strong': return '**%s**' % text
if tag=='em' or tag=='i': return '*%s*' % text
if tag=='tt' or tag=='code': return '`%s`' % text
if tag=='a': return '[%s](%s)' % (text,attr.get('_href',''))
if tag=='img': return '![%s](%s)' % (attr.get('_alt',''),attr.get('_src',''))
return text
def markmin_serializer(text,tag=None,attr={}):
def markmin_serializer(text,tag=None,attr=None):
attr = attr or {}
# if tag is None: return re.sub('\s+',' ',text)
if tag=='br': return '\n\n'
if tag=='h1': return '# '+text+'\n\n'
if tag=='h2': return '#'*2+' '+text+'\n\n'
if tag=='h3': return '#'*3+' '+text+'\n\n'
if tag=='h4': return '#'*4+' '+text+'\n\n'
if tag=='p': return text+'\n\n'
|
︙ | | |
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
|
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
|
-
+
-
-
+
+
|
return text
class MARKMIN(XmlComponent):
"""
For documentation: http://web2py.com/examples/static/markmin.html
"""
def __init__(self, text, extra={}, allowed={}, sep='p'):
def __init__(self, text, extra=None, allowed=None, sep='p'):
self.text = text
self.extra = extra
self.allowed = allowed
self.extra = extra or {}
self.allowed = allowed or {}
self.sep = sep
def xml(self):
"""
calls the gluon.contrib.markmin render function to convert the wiki syntax
"""
return render(self.text,extra=self.extra,allowed=self.allowed,sep=self.sep)
|
︙ | | |
2232
2233
2234
2235
2236
2237
2238
2239
|
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
|
+
+
|
"""
return [self.text]
if __name__ == '__main__':
import doctest
doctest.testmod()
|