PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/gluon/validators.py

https://github.com/clach04/web2py
Python | 3345 lines | 3161 code | 73 blank | 111 comment | 141 complexity | 027af7eaa8b23e00fec75b040c3c1645 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. #!/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. This file is part of the web2py Web Framework
  5. Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
  6. License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
  7. Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE
  8. """
  9. import os
  10. import re
  11. import datetime
  12. import time
  13. import cgi
  14. import urllib
  15. import struct
  16. import decimal
  17. import unicodedata
  18. from cStringIO import StringIO
  19. from utils import simple_hash, web2py_uuid, DIGEST_ALG_BY_SIZE
  20. from dal import FieldVirtual, FieldMethod
  21. JSONErrors = (NameError, TypeError, ValueError, AttributeError,
  22. KeyError)
  23. try:
  24. import json as simplejson
  25. except ImportError:
  26. from gluon.contrib import simplejson
  27. from gluon.contrib.simplejson.decoder import JSONDecodeError
  28. JSONErrors += (JSONDecodeError,)
  29. __all__ = [
  30. 'CLEANUP',
  31. 'CRYPT',
  32. 'IS_ALPHANUMERIC',
  33. 'IS_DATE_IN_RANGE',
  34. 'IS_DATE',
  35. 'IS_DATETIME_IN_RANGE',
  36. 'IS_DATETIME',
  37. 'IS_DECIMAL_IN_RANGE',
  38. 'IS_EMAIL',
  39. 'IS_EMPTY_OR',
  40. 'IS_EXPR',
  41. 'IS_FLOAT_IN_RANGE',
  42. 'IS_IMAGE',
  43. 'IS_IN_DB',
  44. 'IS_IN_SET',
  45. 'IS_INT_IN_RANGE',
  46. 'IS_IPV4',
  47. 'IS_LENGTH',
  48. 'IS_LIST_OF',
  49. 'IS_LOWER',
  50. 'IS_MATCH',
  51. 'IS_EQUAL_TO',
  52. 'IS_NOT_EMPTY',
  53. 'IS_NOT_IN_DB',
  54. 'IS_NULL_OR',
  55. 'IS_SLUG',
  56. 'IS_STRONG',
  57. 'IS_TIME',
  58. 'IS_UPLOAD_FILENAME',
  59. 'IS_UPPER',
  60. 'IS_URL',
  61. 'IS_JSON',
  62. ]
  63. try:
  64. from globals import current
  65. have_current = True
  66. except ImportError:
  67. have_current = False
  68. def translate(text):
  69. if text is None:
  70. return None
  71. elif isinstance(text, (str, unicode)) and have_current:
  72. if hasattr(current, 'T'):
  73. return str(current.T(text))
  74. return str(text)
  75. def options_sorter(x, y):
  76. return (str(x[1]).upper() > str(y[1]).upper() and 1) or -1
  77. class Validator(object):
  78. """
  79. Root for all validators, mainly for documentation purposes.
  80. Validators are classes used to validate input fields (including forms
  81. generated from database tables).
  82. Here is an example of using a validator with a FORM::
  83. INPUT(_name='a', requires=IS_INT_IN_RANGE(0, 10))
  84. Here is an example of how to require a validator for a table field::
  85. db.define_table('person', SQLField('name'))
  86. db.person.name.requires=IS_NOT_EMPTY()
  87. Validators are always assigned using the requires attribute of a field. A
  88. field can have a single validator or multiple validators. Multiple
  89. validators are made part of a list::
  90. db.person.name.requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'person.id')]
  91. Validators are called by the function accepts on a FORM or other HTML
  92. helper object that contains a form. They are always called in the order in
  93. which they are listed.
  94. Built-in validators have constructors that take the optional argument error
  95. message which allows you to change the default error message.
  96. Here is an example of a validator on a database table::
  97. db.person.name.requires=IS_NOT_EMPTY(error_message=T('fill this'))
  98. where we have used the translation operator T to allow for
  99. internationalization.
  100. Notice that default error messages are not translated.
  101. """
  102. def formatter(self, value):
  103. """
  104. For some validators returns a formatted version (matching the validator)
  105. of value. Otherwise just returns the value.
  106. """
  107. return value
  108. def __call__(self, value):
  109. raise NotImplementedError
  110. return (value, None)
  111. class IS_MATCH(Validator):
  112. """
  113. example::
  114. INPUT(_type='text', _name='name', requires=IS_MATCH('.+'))
  115. the argument of IS_MATCH is a regular expression::
  116. >>> IS_MATCH('.+')('hello')
  117. ('hello', None)
  118. >>> IS_MATCH('hell')('hello')
  119. ('hello', None)
  120. >>> IS_MATCH('hell.*', strict=False)('hello')
  121. ('hello', None)
  122. >>> IS_MATCH('hello')('shello')
  123. ('shello', 'invalid expression')
  124. >>> IS_MATCH('hello', search=True)('shello')
  125. ('shello', None)
  126. >>> IS_MATCH('hello', search=True, strict=False)('shellox')
  127. ('shellox', None)
  128. >>> IS_MATCH('.*hello.*', search=True, strict=False)('shellox')
  129. ('shellox', None)
  130. >>> IS_MATCH('.+')('')
  131. ('', 'invalid expression')
  132. """
  133. def __init__(self, expression, error_message='invalid expression',
  134. strict=False, search=False, extract=False):
  135. if strict or not search:
  136. if not expression.startswith('^'):
  137. expression = '^(%s)' % expression
  138. if strict:
  139. if not expression.endswith('$'):
  140. expression = '(%s)$' % expression
  141. self.regex = re.compile(expression)
  142. self.error_message = error_message
  143. self.extract = extract
  144. def __call__(self, value):
  145. match = self.regex.search(value)
  146. if match is not None:
  147. return (self.extract and match.group() or value, None)
  148. return (value, translate(self.error_message))
  149. class IS_EQUAL_TO(Validator):
  150. """
  151. example::
  152. INPUT(_type='text', _name='password')
  153. INPUT(_type='text', _name='password2',
  154. requires=IS_EQUAL_TO(request.vars.password))
  155. the argument of IS_EQUAL_TO is a string
  156. >>> IS_EQUAL_TO('aaa')('aaa')
  157. ('aaa', None)
  158. >>> IS_EQUAL_TO('aaa')('aab')
  159. ('aab', 'no match')
  160. """
  161. def __init__(self, expression, error_message='no match'):
  162. self.expression = expression
  163. self.error_message = error_message
  164. def __call__(self, value):
  165. if value == self.expression:
  166. return (value, None)
  167. return (value, translate(self.error_message))
  168. class IS_EXPR(Validator):
  169. """
  170. example::
  171. INPUT(_type='text', _name='name',
  172. requires=IS_EXPR('5 < int(value) < 10'))
  173. the argument of IS_EXPR must be python condition::
  174. >>> IS_EXPR('int(value) < 2')('1')
  175. ('1', None)
  176. >>> IS_EXPR('int(value) < 2')('2')
  177. ('2', 'invalid expression')
  178. """
  179. def __init__(self, expression, error_message='invalid expression', environment=None):
  180. self.expression = expression
  181. self.error_message = error_message
  182. self.environment = environment or {}
  183. def __call__(self, value):
  184. if callable(self.expression):
  185. return (value, self.expression(value))
  186. # for backward compatibility
  187. self.environment.update(value=value)
  188. exec '__ret__=' + self.expression in self.environment
  189. if self.environment['__ret__']:
  190. return (value, None)
  191. return (value, translate(self.error_message))
  192. class IS_LENGTH(Validator):
  193. """
  194. Checks if length of field's value fits between given boundaries. Works
  195. for both text and file inputs.
  196. Arguments:
  197. maxsize: maximum allowed length / size
  198. minsize: minimum allowed length / size
  199. Examples::
  200. #Check if text string is shorter than 33 characters:
  201. INPUT(_type='text', _name='name', requires=IS_LENGTH(32))
  202. #Check if password string is longer than 5 characters:
  203. INPUT(_type='password', _name='name', requires=IS_LENGTH(minsize=6))
  204. #Check if uploaded file has size between 1KB and 1MB:
  205. INPUT(_type='file', _name='name', requires=IS_LENGTH(1048576, 1024))
  206. >>> IS_LENGTH()('')
  207. ('', None)
  208. >>> IS_LENGTH()('1234567890')
  209. ('1234567890', None)
  210. >>> IS_LENGTH(maxsize=5, minsize=0)('1234567890') # too long
  211. ('1234567890', 'enter from 0 to 5 characters')
  212. >>> IS_LENGTH(maxsize=50, minsize=20)('1234567890') # too short
  213. ('1234567890', 'enter from 20 to 50 characters')
  214. """
  215. def __init__(self, maxsize=255, minsize=0,
  216. error_message='enter from %(min)g to %(max)g characters'):
  217. self.maxsize = maxsize
  218. self.minsize = minsize
  219. self.error_message = error_message
  220. def __call__(self, value):
  221. if value is None:
  222. length = 0
  223. if self.minsize <= length <= self.maxsize:
  224. return (value, None)
  225. elif isinstance(value, cgi.FieldStorage):
  226. if value.file:
  227. value.file.seek(0, os.SEEK_END)
  228. length = value.file.tell()
  229. value.file.seek(0, os.SEEK_SET)
  230. elif hasattr(value, 'value'):
  231. val = value.value
  232. if val:
  233. length = len(val)
  234. else:
  235. length = 0
  236. if self.minsize <= length <= self.maxsize:
  237. return (value, None)
  238. elif isinstance(value, (str, unicode, list)):
  239. if self.minsize <= len(value) <= self.maxsize:
  240. return (value, None)
  241. elif self.minsize <= len(str(value)) <= self.maxsize:
  242. try:
  243. value.decode('utf8')
  244. return (value, None)
  245. except:
  246. pass
  247. return (value, translate(self.error_message)
  248. % dict(min=self.minsize, max=self.maxsize))
  249. class IS_JSON(Validator):
  250. """
  251. example::
  252. INPUT(_type='text', _name='name',
  253. requires=IS_JSON(error_message="This is not a valid json input")
  254. >>> IS_JSON()('{"a": 100}')
  255. ('{"a": 100}', None)
  256. >>> IS_JSON()('spam1234')
  257. ('spam1234', 'invalid json')
  258. """
  259. def __init__(self, error_message='invalid json'):
  260. self.error_message = error_message
  261. def __call__(self, value):
  262. if value is None:
  263. return None
  264. try:
  265. return (simplejson.loads(value), None)
  266. except JSONErrors:
  267. return (value, translate(self.error_message))
  268. def formatter(self,value):
  269. if value is None:
  270. return None
  271. return simplejson.dumps(value)
  272. class IS_IN_SET(Validator):
  273. """
  274. example::
  275. INPUT(_type='text', _name='name',
  276. requires=IS_IN_SET(['max', 'john'],zero=''))
  277. the argument of IS_IN_SET must be a list or set
  278. >>> IS_IN_SET(['max', 'john'])('max')
  279. ('max', None)
  280. >>> IS_IN_SET(['max', 'john'])('massimo')
  281. ('massimo', 'value not allowed')
  282. >>> IS_IN_SET(['max', 'john'], multiple=True)(('max', 'john'))
  283. (('max', 'john'), None)
  284. >>> IS_IN_SET(['max', 'john'], multiple=True)(('bill', 'john'))
  285. (('bill', 'john'), 'value not allowed')
  286. >>> IS_IN_SET(('id1','id2'), ['first label','second label'])('id1') # Traditional way
  287. ('id1', None)
  288. >>> IS_IN_SET({'id1':'first label', 'id2':'second label'})('id1')
  289. ('id1', None)
  290. >>> import itertools
  291. >>> IS_IN_SET(itertools.chain(['1','3','5'],['2','4','6']))('1')
  292. ('1', None)
  293. >>> IS_IN_SET([('id1','first label'), ('id2','second label')])('id1') # Redundant way
  294. ('id1', None)
  295. """
  296. def __init__(
  297. self,
  298. theset,
  299. labels=None,
  300. error_message='value not allowed',
  301. multiple=False,
  302. zero='',
  303. sort=False,
  304. ):
  305. self.multiple = multiple
  306. if isinstance(theset, dict):
  307. self.theset = [str(item) for item in theset]
  308. self.labels = theset.values()
  309. elif theset and isinstance(theset, (tuple, list)) \
  310. and isinstance(theset[0], (tuple, list)) and len(theset[0]) == 2:
  311. self.theset = [str(item) for item, label in theset]
  312. self.labels = [str(label) for item, label in theset]
  313. else:
  314. self.theset = [str(item) for item in theset]
  315. self.labels = labels
  316. self.error_message = error_message
  317. self.zero = zero
  318. self.sort = sort
  319. def options(self, zero=True):
  320. if not self.labels:
  321. items = [(k, k) for (i, k) in enumerate(self.theset)]
  322. else:
  323. items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)]
  324. if self.sort:
  325. items.sort(options_sorter)
  326. if zero and not self.zero is None and not self.multiple:
  327. items.insert(0, ('', self.zero))
  328. return items
  329. def __call__(self, value):
  330. if self.multiple:
  331. ### if below was values = re.compile("[\w\-:]+").findall(str(value))
  332. if not value:
  333. values = []
  334. elif isinstance(value, (tuple, list)):
  335. values = value
  336. else:
  337. values = [value]
  338. else:
  339. values = [value]
  340. thestrset = [str(x) for x in self.theset]
  341. failures = [x for x in values if not str(x) in thestrset]
  342. if failures and self.theset:
  343. if self.multiple and (value is None or value == ''):
  344. return ([], None)
  345. return (value, translate(self.error_message))
  346. if self.multiple:
  347. if isinstance(self.multiple, (tuple, list)) and \
  348. not self.multiple[0] <= len(values) < self.multiple[1]:
  349. return (values, translate(self.error_message))
  350. return (values, None)
  351. return (value, None)
  352. regex1 = re.compile('\w+\.\w+')
  353. regex2 = re.compile('%\((?P<name>[^\)]+)\)s')
  354. class IS_IN_DB(Validator):
  355. """
  356. example::
  357. INPUT(_type='text', _name='name',
  358. requires=IS_IN_DB(db, db.mytable.myfield, zero=''))
  359. used for reference fields, rendered as a dropbox
  360. """
  361. def __init__(
  362. self,
  363. dbset,
  364. field,
  365. label=None,
  366. error_message='value not in database',
  367. orderby=None,
  368. groupby=None,
  369. distinct=None,
  370. cache=None,
  371. multiple=False,
  372. zero='',
  373. sort=False,
  374. _and=None,
  375. ):
  376. from dal import Table
  377. if isinstance(field, Table):
  378. field = field._id
  379. if hasattr(dbset, 'define_table'):
  380. self.dbset = dbset()
  381. else:
  382. self.dbset = dbset
  383. (ktable, kfield) = str(field).split('.')
  384. if not label:
  385. label = '%%(%s)s' % kfield
  386. if isinstance(label, str):
  387. if regex1.match(str(label)):
  388. label = '%%(%s)s' % str(label).split('.')[-1]
  389. ks = regex2.findall(label)
  390. if not kfield in ks:
  391. ks += [kfield]
  392. fields = ks
  393. else:
  394. ks = [kfield]
  395. fields = 'all'
  396. self.fields = fields
  397. self.label = label
  398. self.ktable = ktable
  399. self.kfield = kfield
  400. self.ks = ks
  401. self.error_message = error_message
  402. self.theset = None
  403. self.orderby = orderby
  404. self.groupby = groupby
  405. self.distinct = distinct
  406. self.cache = cache
  407. self.multiple = multiple
  408. self.zero = zero
  409. self.sort = sort
  410. self._and = _and
  411. def set_self_id(self, id):
  412. if self._and:
  413. self._and.record_id = id
  414. def build_set(self):
  415. table = self.dbset.db[self.ktable]
  416. if self.fields == 'all':
  417. fields = [f for f in table]
  418. else:
  419. fields = [table[k] for k in self.fields]
  420. ignore = (FieldVirtual,FieldMethod)
  421. fields = filter(lambda f:not isinstance(f,ignore), fields)
  422. if self.dbset.db._dbname != 'gae':
  423. orderby = self.orderby or reduce(lambda a, b: a | b, fields)
  424. groupby = self.groupby
  425. distinct = self.distinct
  426. dd = dict(orderby=orderby, groupby=groupby,
  427. distinct=distinct, cache=self.cache,
  428. cacheable=True)
  429. records = self.dbset(table).select(*fields, **dd)
  430. else:
  431. orderby = self.orderby or \
  432. reduce(lambda a, b: a | b, (
  433. f for f in fields if not f.name == 'id'))
  434. dd = dict(orderby=orderby, cache=self.cache, cacheable=True)
  435. records = self.dbset(table).select(table.ALL, **dd)
  436. self.theset = [str(r[self.kfield]) for r in records]
  437. if isinstance(self.label, str):
  438. self.labels = [self.label % dict(r) for r in records]
  439. else:
  440. self.labels = [self.label(r) for r in records]
  441. def options(self, zero=True):
  442. self.build_set()
  443. items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)]
  444. if self.sort:
  445. items.sort(options_sorter)
  446. if zero and not self.zero is None and not self.multiple:
  447. items.insert(0, ('', self.zero))
  448. return items
  449. def __call__(self, value):
  450. table = self.dbset.db[self.ktable]
  451. field = table[self.kfield]
  452. if self.multiple:
  453. if self._and:
  454. raise NotImplementedError
  455. if isinstance(value, list):
  456. values = value
  457. elif value:
  458. values = [value]
  459. else:
  460. values = []
  461. if isinstance(self.multiple, (tuple, list)) and \
  462. not self.multiple[0] <= len(values) < self.multiple[1]:
  463. return (values, translate(self.error_message))
  464. if self.theset:
  465. if not [v for v in values if not v in self.theset]:
  466. return (values, None)
  467. else:
  468. from dal import GoogleDatastoreAdapter
  469. def count(values, s=self.dbset, f=field):
  470. return s(f.belongs(map(int, values))).count()
  471. if isinstance(self.dbset.db._adapter, GoogleDatastoreAdapter):
  472. range_ids = range(0, len(values), 30)
  473. total = sum(count(values[i:i + 30]) for i in range_ids)
  474. if total == len(values):
  475. return (values, None)
  476. elif count(values) == len(values):
  477. return (values, None)
  478. elif self.theset:
  479. if str(value) in self.theset:
  480. if self._and:
  481. return self._and(value)
  482. else:
  483. return (value, None)
  484. else:
  485. if self.dbset(field == value).count():
  486. if self._and:
  487. return self._and(value)
  488. else:
  489. return (value, None)
  490. return (value, translate(self.error_message))
  491. class IS_NOT_IN_DB(Validator):
  492. """
  493. example::
  494. INPUT(_type='text', _name='name', requires=IS_NOT_IN_DB(db, db.table))
  495. makes the field unique
  496. """
  497. def __init__(
  498. self,
  499. dbset,
  500. field,
  501. error_message='value already in database or empty',
  502. allowed_override=[],
  503. ignore_common_filters=False,
  504. ):
  505. from dal import Table
  506. if isinstance(field, Table):
  507. field = field._id
  508. if hasattr(dbset, 'define_table'):
  509. self.dbset = dbset()
  510. else:
  511. self.dbset = dbset
  512. self.field = field
  513. self.error_message = error_message
  514. self.record_id = 0
  515. self.allowed_override = allowed_override
  516. self.ignore_common_filters = ignore_common_filters
  517. def set_self_id(self, id):
  518. self.record_id = id
  519. def __call__(self, value):
  520. if isinstance(value,unicode):
  521. value = value.encode('utf8')
  522. else:
  523. value = str(value)
  524. if not value.strip():
  525. return (value, translate(self.error_message))
  526. if value in self.allowed_override:
  527. return (value, None)
  528. (tablename, fieldname) = str(self.field).split('.')
  529. table = self.dbset.db[tablename]
  530. field = table[fieldname]
  531. subset = self.dbset(field == value,
  532. ignore_common_filters=self.ignore_common_filters)
  533. id = self.record_id
  534. if isinstance(id, dict):
  535. fields = [table[f] for f in id]
  536. row = subset.select(*fields, **dict(limitby=(0, 1))).first()
  537. if row and any(str(row[f]) != str(id[f]) for f in id):
  538. return (value, translate(self.error_message))
  539. else:
  540. row = subset.select(table._id, limitby=(0, 1)).first()
  541. if row and str(row.id) != str(id):
  542. return (value, translate(self.error_message))
  543. return (value, None)
  544. class IS_INT_IN_RANGE(Validator):
  545. """
  546. Determine that the argument is (or can be represented as) an int,
  547. and that it falls within the specified range. The range is interpreted
  548. in the Pythonic way, so the test is: min <= value < max.
  549. The minimum and maximum limits can be None, meaning no lower or upper limit,
  550. respectively.
  551. example::
  552. INPUT(_type='text', _name='name', requires=IS_INT_IN_RANGE(0, 10))
  553. >>> IS_INT_IN_RANGE(1,5)('4')
  554. (4, None)
  555. >>> IS_INT_IN_RANGE(1,5)(4)
  556. (4, None)
  557. >>> IS_INT_IN_RANGE(1,5)(1)
  558. (1, None)
  559. >>> IS_INT_IN_RANGE(1,5)(5)
  560. (5, 'enter an integer between 1 and 4')
  561. >>> IS_INT_IN_RANGE(1,5)(5)
  562. (5, 'enter an integer between 1 and 4')
  563. >>> IS_INT_IN_RANGE(1,5)(3.5)
  564. (3, 'enter an integer between 1 and 4')
  565. >>> IS_INT_IN_RANGE(None,5)('4')
  566. (4, None)
  567. >>> IS_INT_IN_RANGE(None,5)('6')
  568. (6, 'enter an integer less than or equal to 4')
  569. >>> IS_INT_IN_RANGE(1,None)('4')
  570. (4, None)
  571. >>> IS_INT_IN_RANGE(1,None)('0')
  572. (0, 'enter an integer greater than or equal to 1')
  573. >>> IS_INT_IN_RANGE()(6)
  574. (6, None)
  575. >>> IS_INT_IN_RANGE()('abc')
  576. ('abc', 'enter an integer')
  577. """
  578. def __init__(
  579. self,
  580. minimum=None,
  581. maximum=None,
  582. error_message=None,
  583. ):
  584. self.minimum = self.maximum = None
  585. if minimum is None:
  586. if maximum is None:
  587. self.error_message = error_message or 'enter an integer'
  588. else:
  589. self.maximum = int(maximum)
  590. if error_message is None:
  591. error_message = 'enter an integer less than or equal to %(max)g'
  592. self.error_message = translate(
  593. error_message) % dict(max=self.maximum - 1)
  594. elif maximum is None:
  595. self.minimum = int(minimum)
  596. if error_message is None:
  597. error_message = 'enter an integer greater than or equal to %(min)g'
  598. self.error_message = translate(
  599. error_message) % dict(min=self.minimum)
  600. else:
  601. self.minimum = int(minimum)
  602. self.maximum = int(maximum)
  603. if error_message is None:
  604. error_message = 'enter an integer between %(min)g and %(max)g'
  605. self.error_message = translate(error_message) \
  606. % dict(min=self.minimum, max=self.maximum - 1)
  607. def __call__(self, value):
  608. try:
  609. fvalue = float(value)
  610. value = int(value)
  611. if value != fvalue:
  612. return (value, self.error_message)
  613. if self.minimum is None:
  614. if self.maximum is None or value < self.maximum:
  615. return (value, None)
  616. elif self.maximum is None:
  617. if value >= self.minimum:
  618. return (value, None)
  619. elif self.minimum <= value < self.maximum:
  620. return (value, None)
  621. except ValueError:
  622. pass
  623. return (value, self.error_message)
  624. def str2dec(number):
  625. s = str(number)
  626. if not '.' in s:
  627. s += '.00'
  628. else:
  629. s += '0' * (2 - len(s.split('.')[1]))
  630. return s
  631. class IS_FLOAT_IN_RANGE(Validator):
  632. """
  633. Determine that the argument is (or can be represented as) a float,
  634. and that it falls within the specified inclusive range.
  635. The comparison is made with native arithmetic.
  636. The minimum and maximum limits can be None, meaning no lower or upper limit,
  637. respectively.
  638. example::
  639. INPUT(_type='text', _name='name', requires=IS_FLOAT_IN_RANGE(0, 10))
  640. >>> IS_FLOAT_IN_RANGE(1,5)('4')
  641. (4.0, None)
  642. >>> IS_FLOAT_IN_RANGE(1,5)(4)
  643. (4.0, None)
  644. >>> IS_FLOAT_IN_RANGE(1,5)(1)
  645. (1.0, None)
  646. >>> IS_FLOAT_IN_RANGE(1,5)(5.25)
  647. (5.25, 'enter a number between 1 and 5')
  648. >>> IS_FLOAT_IN_RANGE(1,5)(6.0)
  649. (6.0, 'enter a number between 1 and 5')
  650. >>> IS_FLOAT_IN_RANGE(1,5)(3.5)
  651. (3.5, None)
  652. >>> IS_FLOAT_IN_RANGE(1,None)(3.5)
  653. (3.5, None)
  654. >>> IS_FLOAT_IN_RANGE(None,5)(3.5)
  655. (3.5, None)
  656. >>> IS_FLOAT_IN_RANGE(1,None)(0.5)
  657. (0.5, 'enter a number greater than or equal to 1')
  658. >>> IS_FLOAT_IN_RANGE(None,5)(6.5)
  659. (6.5, 'enter a number less than or equal to 5')
  660. >>> IS_FLOAT_IN_RANGE()(6.5)
  661. (6.5, None)
  662. >>> IS_FLOAT_IN_RANGE()('abc')
  663. ('abc', 'enter a number')
  664. """
  665. def __init__(
  666. self,
  667. minimum=None,
  668. maximum=None,
  669. error_message=None,
  670. dot='.'
  671. ):
  672. self.minimum = self.maximum = None
  673. self.dot = dot
  674. if minimum is None:
  675. if maximum is None:
  676. if error_message is None:
  677. error_message = 'enter a number'
  678. else:
  679. self.maximum = float(maximum)
  680. if error_message is None:
  681. error_message = 'enter a number less than or equal to %(max)g'
  682. elif maximum is None:
  683. self.minimum = float(minimum)
  684. if error_message is None:
  685. error_message = 'enter a number greater than or equal to %(min)g'
  686. else:
  687. self.minimum = float(minimum)
  688. self.maximum = float(maximum)
  689. if error_message is None:
  690. error_message = 'enter a number between %(min)g and %(max)g'
  691. self.error_message = translate(error_message) \
  692. % dict(min=self.minimum, max=self.maximum)
  693. def __call__(self, value):
  694. try:
  695. if self.dot == '.':
  696. fvalue = float(value)
  697. else:
  698. fvalue = float(str(value).replace(self.dot, '.'))
  699. if self.minimum is None:
  700. if self.maximum is None or fvalue <= self.maximum:
  701. return (fvalue, None)
  702. elif self.maximum is None:
  703. if fvalue >= self.minimum:
  704. return (fvalue, None)
  705. elif self.minimum <= fvalue <= self.maximum:
  706. return (fvalue, None)
  707. except (ValueError, TypeError):
  708. pass
  709. return (value, self.error_message)
  710. def formatter(self, value):
  711. if value is None:
  712. return None
  713. return str2dec(value).replace('.', self.dot)
  714. class IS_DECIMAL_IN_RANGE(Validator):
  715. """
  716. Determine that the argument is (or can be represented as) a Python Decimal,
  717. and that it falls within the specified inclusive range.
  718. The comparison is made with Python Decimal arithmetic.
  719. The minimum and maximum limits can be None, meaning no lower or upper limit,
  720. respectively.
  721. example::
  722. INPUT(_type='text', _name='name', requires=IS_DECIMAL_IN_RANGE(0, 10))
  723. >>> IS_DECIMAL_IN_RANGE(1,5)('4')
  724. (Decimal('4'), None)
  725. >>> IS_DECIMAL_IN_RANGE(1,5)(4)
  726. (Decimal('4'), None)
  727. >>> IS_DECIMAL_IN_RANGE(1,5)(1)
  728. (Decimal('1'), None)
  729. >>> IS_DECIMAL_IN_RANGE(1,5)(5.25)
  730. (5.25, 'enter a number between 1 and 5')
  731. >>> IS_DECIMAL_IN_RANGE(5.25,6)(5.25)
  732. (Decimal('5.25'), None)
  733. >>> IS_DECIMAL_IN_RANGE(5.25,6)('5.25')
  734. (Decimal('5.25'), None)
  735. >>> IS_DECIMAL_IN_RANGE(1,5)(6.0)
  736. (6.0, 'enter a number between 1 and 5')
  737. >>> IS_DECIMAL_IN_RANGE(1,5)(3.5)
  738. (Decimal('3.5'), None)
  739. >>> IS_DECIMAL_IN_RANGE(1.5,5.5)(3.5)
  740. (Decimal('3.5'), None)
  741. >>> IS_DECIMAL_IN_RANGE(1.5,5.5)(6.5)
  742. (6.5, 'enter a number between 1.5 and 5.5')
  743. >>> IS_DECIMAL_IN_RANGE(1.5,None)(6.5)
  744. (Decimal('6.5'), None)
  745. >>> IS_DECIMAL_IN_RANGE(1.5,None)(0.5)
  746. (0.5, 'enter a number greater than or equal to 1.5')
  747. >>> IS_DECIMAL_IN_RANGE(None,5.5)(4.5)
  748. (Decimal('4.5'), None)
  749. >>> IS_DECIMAL_IN_RANGE(None,5.5)(6.5)
  750. (6.5, 'enter a number less than or equal to 5.5')
  751. >>> IS_DECIMAL_IN_RANGE()(6.5)
  752. (Decimal('6.5'), None)
  753. >>> IS_DECIMAL_IN_RANGE(0,99)(123.123)
  754. (123.123, 'enter a number between 0 and 99')
  755. >>> IS_DECIMAL_IN_RANGE(0,99)('123.123')
  756. ('123.123', 'enter a number between 0 and 99')
  757. >>> IS_DECIMAL_IN_RANGE(0,99)('12.34')
  758. (Decimal('12.34'), None)
  759. >>> IS_DECIMAL_IN_RANGE()('abc')
  760. ('abc', 'enter a decimal number')
  761. """
  762. def __init__(
  763. self,
  764. minimum=None,
  765. maximum=None,
  766. error_message=None,
  767. dot='.'
  768. ):
  769. self.minimum = self.maximum = None
  770. self.dot = dot
  771. if minimum is None:
  772. if maximum is None:
  773. if error_message is None:
  774. error_message = 'enter a decimal number'
  775. else:
  776. self.maximum = decimal.Decimal(str(maximum))
  777. if error_message is None:
  778. error_message = 'enter a number less than or equal to %(max)g'
  779. elif maximum is None:
  780. self.minimum = decimal.Decimal(str(minimum))
  781. if error_message is None:
  782. error_message = 'enter a number greater than or equal to %(min)g'
  783. else:
  784. self.minimum = decimal.Decimal(str(minimum))
  785. self.maximum = decimal.Decimal(str(maximum))
  786. if error_message is None:
  787. error_message = 'enter a number between %(min)g and %(max)g'
  788. self.error_message = translate(error_message) \
  789. % dict(min=self.minimum, max=self.maximum)
  790. def __call__(self, value):
  791. try:
  792. if isinstance(value, decimal.Decimal):
  793. v = value
  794. else:
  795. v = decimal.Decimal(str(value).replace(self.dot, '.'))
  796. if self.minimum is None:
  797. if self.maximum is None or v <= self.maximum:
  798. return (v, None)
  799. elif self.maximum is None:
  800. if v >= self.minimum:
  801. return (v, None)
  802. elif self.minimum <= v <= self.maximum:
  803. return (v, None)
  804. except (ValueError, TypeError, decimal.InvalidOperation):
  805. pass
  806. return (value, self.error_message)
  807. def formatter(self, value):
  808. if value is None:
  809. return None
  810. return str2dec(value).replace('.', self.dot)
  811. def is_empty(value, empty_regex=None):
  812. "test empty field"
  813. if isinstance(value, (str, unicode)):
  814. value = value.strip()
  815. if empty_regex is not None and empty_regex.match(value):
  816. value = ''
  817. if value is None or value == '' or value == []:
  818. return (value, True)
  819. return (value, False)
  820. class IS_NOT_EMPTY(Validator):
  821. """
  822. example::
  823. INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY())
  824. >>> IS_NOT_EMPTY()(1)
  825. (1, None)
  826. >>> IS_NOT_EMPTY()(0)
  827. (0, None)
  828. >>> IS_NOT_EMPTY()('x')
  829. ('x', None)
  830. >>> IS_NOT_EMPTY()(' x ')
  831. ('x', None)
  832. >>> IS_NOT_EMPTY()(None)
  833. (None, 'enter a value')
  834. >>> IS_NOT_EMPTY()('')
  835. ('', 'enter a value')
  836. >>> IS_NOT_EMPTY()(' ')
  837. ('', 'enter a value')
  838. >>> IS_NOT_EMPTY()(' \\n\\t')
  839. ('', 'enter a value')
  840. >>> IS_NOT_EMPTY()([])
  841. ([], 'enter a value')
  842. >>> IS_NOT_EMPTY(empty_regex='def')('def')
  843. ('', 'enter a value')
  844. >>> IS_NOT_EMPTY(empty_regex='de[fg]')('deg')
  845. ('', 'enter a value')
  846. >>> IS_NOT_EMPTY(empty_regex='def')('abc')
  847. ('abc', None)
  848. """
  849. def __init__(self, error_message='enter a value', empty_regex=None):
  850. self.error_message = error_message
  851. if empty_regex is not None:
  852. self.empty_regex = re.compile(empty_regex)
  853. else:
  854. self.empty_regex = None
  855. def __call__(self, value):
  856. value, empty = is_empty(value, empty_regex=self.empty_regex)
  857. if empty:
  858. return (value, translate(self.error_message))
  859. return (value, None)
  860. class IS_ALPHANUMERIC(IS_MATCH):
  861. """
  862. example::
  863. INPUT(_type='text', _name='name', requires=IS_ALPHANUMERIC())
  864. >>> IS_ALPHANUMERIC()('1')
  865. ('1', None)
  866. >>> IS_ALPHANUMERIC()('')
  867. ('', None)
  868. >>> IS_ALPHANUMERIC()('A_a')
  869. ('A_a', None)
  870. >>> IS_ALPHANUMERIC()('!')
  871. ('!', 'enter only letters, numbers, and underscore')
  872. """
  873. def __init__(self, error_message='enter only letters, numbers, and underscore'):
  874. IS_MATCH.__init__(self, '^[\w]*$', error_message)
  875. class IS_EMAIL(Validator):
  876. """
  877. Checks if field's value is a valid email address. Can be set to disallow
  878. or force addresses from certain domain(s).
  879. Email regex adapted from
  880. http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx,
  881. generally following the RFCs, except that we disallow quoted strings
  882. and permit underscores and leading numerics in subdomain labels
  883. Arguments:
  884. - banned: regex text for disallowed address domains
  885. - forced: regex text for required address domains
  886. Both arguments can also be custom objects with a match(value) method.
  887. Examples::
  888. #Check for valid email address:
  889. INPUT(_type='text', _name='name',
  890. requires=IS_EMAIL())
  891. #Check for valid email address that can't be from a .com domain:
  892. INPUT(_type='text', _name='name',
  893. requires=IS_EMAIL(banned='^.*\.com(|\..*)$'))
  894. #Check for valid email address that must be from a .edu domain:
  895. INPUT(_type='text', _name='name',
  896. requires=IS_EMAIL(forced='^.*\.edu(|\..*)$'))
  897. >>> IS_EMAIL()('a@b.com')
  898. ('a@b.com', None)
  899. >>> IS_EMAIL()('abc@def.com')
  900. ('abc@def.com', None)
  901. >>> IS_EMAIL()('abc@3def.com')
  902. ('abc@3def.com', None)
  903. >>> IS_EMAIL()('abc@def.us')
  904. ('abc@def.us', None)
  905. >>> IS_EMAIL()('abc@d_-f.us')
  906. ('abc@d_-f.us', None)
  907. >>> IS_EMAIL()('@def.com') # missing name
  908. ('@def.com', 'enter a valid email address')
  909. >>> IS_EMAIL()('"abc@def".com') # quoted name
  910. ('"abc@def".com', 'enter a valid email address')
  911. >>> IS_EMAIL()('abc+def.com') # no @
  912. ('abc+def.com', 'enter a valid email address')
  913. >>> IS_EMAIL()('abc@def.x') # one-char TLD
  914. ('abc@def.x', 'enter a valid email address')
  915. >>> IS_EMAIL()('abc@def.12') # numeric TLD
  916. ('abc@def.12', 'enter a valid email address')
  917. >>> IS_EMAIL()('abc@def..com') # double-dot in domain
  918. ('abc@def..com', 'enter a valid email address')
  919. >>> IS_EMAIL()('abc@.def.com') # dot starts domain
  920. ('abc@.def.com', 'enter a valid email address')
  921. >>> IS_EMAIL()('abc@def.c_m') # underscore in TLD
  922. ('abc@def.c_m', 'enter a valid email address')
  923. >>> IS_EMAIL()('NotAnEmail') # missing @
  924. ('NotAnEmail', 'enter a valid email address')
  925. >>> IS_EMAIL()('abc@NotAnEmail') # missing TLD
  926. ('abc@NotAnEmail', 'enter a valid email address')
  927. >>> IS_EMAIL()('customer/department@example.com')
  928. ('customer/department@example.com', None)
  929. >>> IS_EMAIL()('$A12345@example.com')
  930. ('$A12345@example.com', None)
  931. >>> IS_EMAIL()('!def!xyz%abc@example.com')
  932. ('!def!xyz%abc@example.com', None)
  933. >>> IS_EMAIL()('_Yosemite.Sam@example.com')
  934. ('_Yosemite.Sam@example.com', None)
  935. >>> IS_EMAIL()('~@example.com')
  936. ('~@example.com', None)
  937. >>> IS_EMAIL()('.wooly@example.com') # dot starts name
  938. ('.wooly@example.com', 'enter a valid email address')
  939. >>> IS_EMAIL()('wo..oly@example.com') # adjacent dots in name
  940. ('wo..oly@example.com', 'enter a valid email address')
  941. >>> IS_EMAIL()('pootietang.@example.com') # dot ends name
  942. ('pootietang.@example.com', 'enter a valid email address')
  943. >>> IS_EMAIL()('.@example.com') # name is bare dot
  944. ('.@example.com', 'enter a valid email address')
  945. >>> IS_EMAIL()('Ima.Fool@example.com')
  946. ('Ima.Fool@example.com', None)
  947. >>> IS_EMAIL()('Ima Fool@example.com') # space in name
  948. ('Ima Fool@example.com', 'enter a valid email address')
  949. >>> IS_EMAIL()('localguy@localhost') # localhost as domain
  950. ('localguy@localhost', None)
  951. """
  952. regex = re.compile('''
  953. ^(?!\.) # name may not begin with a dot
  954. (
  955. [-a-z0-9!\#$%&'*+/=?^_`{|}~] # all legal characters except dot
  956. |
  957. (?<!\.)\. # single dots only
  958. )+
  959. (?<!\.) # name may not end with a dot
  960. @
  961. (
  962. localhost
  963. |
  964. (
  965. [a-z0-9]
  966. # [sub]domain begins with alphanumeric
  967. (
  968. [-\w]* # alphanumeric, underscore, dot, hyphen
  969. [a-z0-9] # ending alphanumeric
  970. )?
  971. \. # ending dot
  972. )+
  973. [a-z]{2,} # TLD alpha-only
  974. )$
  975. ''', re.VERBOSE | re.IGNORECASE)
  976. regex_proposed_but_failed = re.compile('^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$', re.VERBOSE | re.IGNORECASE)
  977. def __init__(self,
  978. banned=None,
  979. forced=None,
  980. error_message='enter a valid email address'):
  981. if isinstance(banned, str):
  982. banned = re.compile(banned)
  983. if isinstance(forced, str):
  984. forced = re.compile(forced)
  985. self.banned = banned
  986. self.forced = forced
  987. self.error_message = error_message
  988. def __call__(self, value):
  989. match = self.regex.match(value)
  990. if match:
  991. domain = value.split('@')[1]
  992. if (not self.banned or not self.banned.match(domain)) \
  993. and (not self.forced or self.forced.match(domain)):
  994. return (value, None)
  995. return (value, translate(self.error_message))
  996. # URL scheme source:
  997. # <http://en.wikipedia.org/wiki/URI_scheme> obtained on 2008-Nov-10
  998. official_url_schemes = [
  999. 'aaa',
  1000. 'aaas',
  1001. 'acap',
  1002. 'cap',
  1003. 'cid',
  1004. 'crid',
  1005. 'data',
  1006. 'dav',
  1007. 'dict',
  1008. 'dns',
  1009. 'fax',
  1010. 'file',
  1011. 'ftp',
  1012. 'go',
  1013. 'gopher',
  1014. 'h323',
  1015. 'http',
  1016. 'https',
  1017. 'icap',
  1018. 'im',
  1019. 'imap',
  1020. 'info',
  1021. 'ipp',
  1022. 'iris',
  1023. 'iris.beep',
  1024. 'iris.xpc',
  1025. 'iris.xpcs',
  1026. 'iris.lws',
  1027. 'ldap',
  1028. 'mailto',
  1029. 'mid',
  1030. 'modem',
  1031. 'msrp',
  1032. 'msrps',
  1033. 'mtqp',
  1034. 'mupdate',
  1035. 'news',
  1036. 'nfs',
  1037. 'nntp',
  1038. 'opaquelocktoken',
  1039. 'pop',
  1040. 'pres',
  1041. 'prospero',
  1042. 'rtsp',
  1043. 'service',
  1044. 'shttp',
  1045. 'sip',
  1046. 'sips',
  1047. 'snmp',
  1048. 'soap.beep',
  1049. 'soap.beeps',
  1050. 'tag',
  1051. 'tel',
  1052. 'telnet',
  1053. 'tftp',
  1054. 'thismessage',
  1055. 'tip',
  1056. 'tv',
  1057. 'urn',
  1058. 'vemmi',
  1059. 'wais',
  1060. 'xmlrpc.beep',
  1061. 'xmlrpc.beep',
  1062. 'xmpp',
  1063. 'z39.50r',
  1064. 'z39.50s',
  1065. ]
  1066. unofficial_url_schemes = [
  1067. 'about',
  1068. 'adiumxtra',
  1069. 'aim',
  1070. 'afp',
  1071. 'aw',
  1072. 'callto',
  1073. 'chrome',
  1074. 'cvs',
  1075. 'ed2k',
  1076. 'feed',
  1077. 'fish',
  1078. 'gg',
  1079. 'gizmoproject',
  1080. 'iax2',
  1081. 'irc',
  1082. 'ircs',
  1083. 'itms',
  1084. 'jar',
  1085. 'javascript',
  1086. 'keyparc',
  1087. 'lastfm',
  1088. 'ldaps',
  1089. 'magnet',
  1090. 'mms',
  1091. 'msnim',
  1092. 'mvn',
  1093. 'notes',
  1094. 'nsfw',
  1095. 'psyc',
  1096. 'paparazzi:http',
  1097. 'rmi',
  1098. 'rsync',
  1099. 'secondlife',
  1100. 'sgn',
  1101. 'skype',
  1102. 'ssh',
  1103. 'sftp',
  1104. 'smb',
  1105. 'sms',
  1106. 'soldat',
  1107. 'steam',
  1108. 'svn',
  1109. 'teamspeak',
  1110. 'unreal',
  1111. 'ut2004',
  1112. 'ventrilo',
  1113. 'view-source',
  1114. 'webcal',
  1115. 'wyciwyg',
  1116. 'xfire',
  1117. 'xri',
  1118. 'ymsgr',
  1119. ]
  1120. all_url_schemes = [None] + official_url_schemes + unofficial_url_schemes
  1121. http_schemes = [None, 'http', 'https']
  1122. # This regex comes from RFC 2396, Appendix B. It's used to split a URL into
  1123. # its component parts
  1124. # Here are the regex groups that it extracts:
  1125. # scheme = group(2)
  1126. # authority = group(4)
  1127. # path = group(5)
  1128. # query = group(7)
  1129. # fragment = group(9)
  1130. url_split_regex = \
  1131. re.compile('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?')
  1132. # Defined in RFC 3490, Section 3.1, Requirement #1
  1133. # Use this regex to split the authority component of a unicode URL into
  1134. # its component labels
  1135. label_split_regex = re.compile(u'[\u002e\u3002\uff0e\uff61]')
  1136. def escape_unicode(string):
  1137. '''
  1138. Converts a unicode string into US-ASCII, using a simple conversion scheme.
  1139. Each unicode character that does not have a US-ASCII equivalent is
  1140. converted into a URL escaped form based on its hexadecimal value.
  1141. For example, the unicode character '\u4e86' will become the string '%4e%86'
  1142. :param string: unicode string, the unicode string to convert into an
  1143. escaped US-ASCII form
  1144. :returns: the US-ASCII escaped form of the inputted string
  1145. :rtype: string
  1146. @author: Jonathan Benn
  1147. '''
  1148. returnValue = StringIO()
  1149. for character in string:
  1150. code = ord(character)
  1151. if code > 0x7F:
  1152. hexCode = hex(code)
  1153. returnValue.write('%' + hexCode[2:4] + '%' + hexCode[4:6])
  1154. else:
  1155. returnValue.write(character)
  1156. return returnValue.getvalue()
  1157. def unicode_to_ascii_authority(authority):
  1158. '''
  1159. Follows the steps in RFC 3490, Section 4 to convert a unicode authority
  1160. string into its ASCII equivalent.
  1161. For example, u'www.Alliancefran\xe7aise.nu' will be converted into
  1162. 'www.xn--alliancefranaise-npb.nu'
  1163. :param authority: unicode string, the URL authority component to convert,
  1164. e.g. u'www.Alliancefran\xe7aise.nu'
  1165. :returns: the US-ASCII character equivalent to the inputed authority,
  1166. e.g. 'www.xn--alliancefranaise-npb.nu'
  1167. :rtype: string
  1168. :raises Exception: if the function is not able to convert the inputed
  1169. authority
  1170. @author: Jonathan Benn
  1171. '''
  1172. #RFC 3490, Section 4, Step 1
  1173. #The encodings.idna Python module assumes that AllowUnassigned == True
  1174. #RFC 3490, Section 4, Step 2
  1175. labels = label_split_regex.split(authority)
  1176. #RFC 3490, Section 4, Step 3
  1177. #The encodings.idna Python module assumes that UseSTD3ASCIIRules == False
  1178. #RFC 3490, Section 4, Step 4
  1179. #We use the ToASCII operation because we are about to put the authority
  1180. #into an IDN-unaware slot
  1181. asciiLabels = []
  1182. try:
  1183. import encodings.idna
  1184. for label in labels:
  1185. if label:
  1186. asciiLabels.append(encodings.idna.ToASCII(label))
  1187. else:
  1188. #encodings.idna.ToASCII does not accept an empty string, but
  1189. #it is necessary for us to allow for empty labels so that we
  1190. #don't modify the URL
  1191. asciiLabels.append('')
  1192. except:
  1193. asciiLabels = [str(label) for label in labels]
  1194. #RFC 3490, Section 4, Step 5
  1195. return str(reduce(lambda x, y: x + unichr(0x002E) + y, asciiLabels))
  1196. def unicode_to_ascii_url(url, prepend_scheme):
  1197. '''
  1198. Converts the inputed unicode url into a US-ASCII equivalent. This function
  1199. goes a little beyond RFC 3490, which is limited in scope to the domain name
  1200. (authority) only. Here, the functionality is expanded to what was observed
  1201. on Wikipedia on 2009-Jan-22:
  1202. Component Can Use Unicode?
  1203. --------- ----------------
  1204. scheme No
  1205. authority Yes
  1206. path Yes
  1207. query Yes
  1208. fragment No
  1209. The authority component gets converted to punycode, but occurrences of
  1210. unicode in other components get converted into a pair of URI escapes (we
  1211. assume 4-byte unicode). E.g. the unicode character U+4E2D will be
  1212. converted into '%4E%2D'. Testing with Firefox v3.0.5 has shown that it can
  1213. understand this kind of URI encoding.
  1214. :param url: unicode string, the URL to convert from unicode into US-ASCII
  1215. :param prepend_scheme: string, a protocol scheme to prepend to the URL if
  1216. we're having trouble parsing it.
  1217. e.g. "http". Input None to disable this functionality
  1218. :returns: a US-ASCII equivalent of the inputed url
  1219. :rtype: string
  1220. @author: Jonathan Benn
  1221. '''
  1222. #convert the authority component of the URL into an ASCII punycode string,
  1223. #but encode the rest using the regular URI character encoding
  1224. groups = url_split_regex.match(url).groups()
  1225. #If no authority was found
  1226. if not groups[3]:
  1227. #Try appending a scheme to see if that fixes the problem
  1228. scheme_to_prepend = prepend_scheme or 'http'
  1229. groups = url_split_regex.match(
  1230. unicode(scheme_to_prepend) + u'://' + url).groups()
  1231. #if we still can't find the authority
  1232. if not groups[3]:
  1233. raise Exception('No authority component found, ' +
  1234. 'could not decode unicode to US-ASCII')
  1235. #We're here if we found an authority, let's rebuild the URL
  1236. scheme = groups[1]
  1237. authority = groups[3]
  1238. path = groups[4] or ''
  1239. query = groups[5] or ''
  1240. fragment = groups[7] or ''
  1241. if prepend_scheme:
  1242. scheme = str(scheme) + '://'
  1243. else:
  1244. scheme = ''
  1245. return scheme + unicode_to_ascii_authority(authority) +\
  1246. escape_unicode(path) + escape_unicode(query) + str(fragment)
  1247. class IS_GENERIC_URL(Validator):
  1248. """
  1249. Rejects a URL string if any of the following is true:
  1250. * The string is empty or None
  1251. * The string uses characters that are not allowed in a URL
  1252. * The URL scheme specified (if one is specified) is not valid
  1253. Based on RFC 2396: http://www.faqs.org/rfcs/rfc2396.html
  1254. This function only checks the URL's syntax. It does not check that the URL
  1255. points to a real document, for example, or that it otherwise makes sense
  1256. semantically. This function does automatically prepend 'http://' in front
  1257. of a URL if and only if that's necessary to successfully parse the URL.
  1258. Please note that a scheme will be prepended only for rare cases
  1259. (e.g. 'google.ca:80')
  1260. The list of allowed schemes is customizable with the allowed_schemes
  1261. parameter. If you exclude None from the list, then abbreviated URLs
  1262. (lacking a scheme such as 'http') will be rejected.
  1263. The default prepended scheme is customizable with the prepend_scheme
  1264. parameter. If you set prepend_scheme to None then prepending will be
  1265. disabled. URLs that require prepending to parse will still be accepted,
  1266. but the return value will not be modified.
  1267. @author: Jonathan Benn
  1268. >>> IS_GENERIC_URL()('http://user@abc.com')
  1269. ('http://user@abc.com', None)
  1270. """
  1271. def __init__(
  1272. self,
  1273. error_message='enter a valid URL',
  1274. allowed_schemes=None,
  1275. prepend_scheme=None,
  1276. ):
  1277. """
  1278. :param error_message: a string, the error message to give the end user
  1279. if the URL does not validate
  1280. :param allowed_schemes: a list containing strings or None. Each element
  1281. is a scheme the inputed URL is allowed to use
  1282. :param prepend_scheme: a string, this scheme is prepended if it's
  1283. necessary to make the URL valid
  1284. """
  1285. self.error_message = error_message
  1286. if allowed_schemes is None:
  1287. self.allowed_schemes = all_url_schemes
  1288. else:
  1289. self.allowed_schemes = allowed_schemes
  1290. self.prepend_scheme = prepend_scheme
  1291. if self.prepend_scheme not in self.allowed_schemes:
  1292. raise SyntaxError("prepend_scheme='%s' is not in allowed_schemes=%s"
  1293. % (self.prepend_scheme, self.allowed_schemes))
  1294. GENERIC_URL = re.compile(r"%[^0-9A-Fa-f]{2}|%[^0-9A-Fa-f][0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]|%$|%[0-9A-Fa-f]$|%[^0-9A-Fa-f]$")
  1295. GENERIC_URL_VALID = re.compile(r"[A-Za-z0-9;/?:@&=+$,\-_\.!~*'\(\)%#]+$")
  1296. def __call__(self, value):
  1297. """
  1298. :param value: a string, the URL to validate
  1299. :returns: a tuple, where tuple[0] is the inputed value (possible
  1300. prepended with prepend_scheme), and tuple[1] is either
  1301. None (success!) or the string error_message
  1302. """
  1303. try:
  1304. # if the URL does not misuse the '%' character
  1305. if not self.GENERIC_URL.search(value):
  1306. # if the URL is only composed of valid characters
  1307. if self.GENERIC_URL_VALID.match(value):
  1308. # Then split up the URL into its components and check on
  1309. # the scheme
  1310. scheme = url_split_regex.match(value).group(2)
  1311. # Clean up the scheme before we check it
  1312. if not scheme is None:
  1313. scheme = urllib.unquote(scheme).lower()
  1314. # If the scheme really exists
  1315. if scheme in self.allowed_schemes:
  1316. # Then the URL is valid
  1317. return (value, None)
  1318. else:
  1319. # else, for the possible case of abbreviated URLs with
  1320. # ports, check to see if adding a valid scheme fixes
  1321. # the problem (but only do this if it doesn't have
  1322. # one already!)
  1323. if value.find('://…

Large files files are truncated, but you can click here to view the full file