formmethod.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # -*- test-case-name: twisted.test.test_formmethod -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Form-based method objects.
  6. This module contains support for descriptive method signatures that can be used
  7. to format methods.
  8. """
  9. import calendar
  10. from twisted.python._oldstyle import _oldStyle
  11. class FormException(Exception):
  12. """An error occurred calling the form method.
  13. """
  14. def __init__(self, *args, **kwargs):
  15. Exception.__init__(self, *args)
  16. self.descriptions = kwargs
  17. class InputError(FormException):
  18. """
  19. An error occurred with some input.
  20. """
  21. @_oldStyle
  22. class Argument:
  23. """Base class for form arguments."""
  24. # default value for argument, if no other default is given
  25. defaultDefault = None
  26. def __init__(self, name, default=None, shortDesc=None,
  27. longDesc=None, hints=None, allowNone=1):
  28. self.name = name
  29. self.allowNone = allowNone
  30. if default is None:
  31. default = self.defaultDefault
  32. self.default = default
  33. self.shortDesc = shortDesc
  34. self.longDesc = longDesc
  35. if not hints:
  36. hints = {}
  37. self.hints = hints
  38. def addHints(self, **kwargs):
  39. self.hints.update(kwargs)
  40. def getHint(self, name, default=None):
  41. return self.hints.get(name, default)
  42. def getShortDescription(self):
  43. return self.shortDesc or self.name.capitalize()
  44. def getLongDescription(self):
  45. return self.longDesc or '' #self.shortDesc or "The %s." % self.name
  46. def coerce(self, val):
  47. """Convert the value to the correct format."""
  48. raise NotImplementedError("implement in subclass")
  49. class String(Argument):
  50. """A single string.
  51. """
  52. defaultDefault = ''
  53. min = 0
  54. max = None
  55. def __init__(self, name, default=None, shortDesc=None,
  56. longDesc=None, hints=None, allowNone=1, min=0, max=None):
  57. Argument.__init__(self, name, default=default, shortDesc=shortDesc,
  58. longDesc=longDesc, hints=hints, allowNone=allowNone)
  59. self.min = min
  60. self.max = max
  61. def coerce(self, val):
  62. s = str(val)
  63. if len(s) < self.min:
  64. raise InputError("Value must be at least %s characters long" % self.min)
  65. if self.max != None and len(s) > self.max:
  66. raise InputError("Value must be at most %s characters long" % self.max)
  67. return str(val)
  68. class Text(String):
  69. """A long string.
  70. """
  71. class Password(String):
  72. """A string which should be obscured when input.
  73. """
  74. class VerifiedPassword(String):
  75. """A string that should be obscured when input and needs verification."""
  76. def coerce(self, vals):
  77. if len(vals) != 2 or vals[0] != vals[1]:
  78. raise InputError("Please enter the same password twice.")
  79. s = str(vals[0])
  80. if len(s) < self.min:
  81. raise InputError("Value must be at least %s characters long" % self.min)
  82. if self.max != None and len(s) > self.max:
  83. raise InputError("Value must be at most %s characters long" % self.max)
  84. return s
  85. class Hidden(String):
  86. """A string which is not displayed.
  87. The passed default is used as the value.
  88. """
  89. class Integer(Argument):
  90. """A single integer.
  91. """
  92. defaultDefault = None
  93. def __init__(self, name, allowNone=1, default=None, shortDesc=None,
  94. longDesc=None, hints=None):
  95. #although Argument now has allowNone, that was recently added, and
  96. #putting it at the end kept things which relied on argument order
  97. #from breaking. However, allowNone originally was in here, so
  98. #I have to keep the same order, to prevent breaking code that
  99. #depends on argument order only
  100. Argument.__init__(self, name, default, shortDesc, longDesc, hints,
  101. allowNone)
  102. def coerce(self, val):
  103. if not val.strip() and self.allowNone:
  104. return None
  105. try:
  106. return int(val)
  107. except ValueError:
  108. raise InputError("%s is not valid, please enter a whole number, e.g. 10" % val)
  109. class IntegerRange(Integer):
  110. def __init__(self, name, min, max, allowNone=1, default=None, shortDesc=None,
  111. longDesc=None, hints=None):
  112. self.min = min
  113. self.max = max
  114. Integer.__init__(self, name, allowNone=allowNone, default=default, shortDesc=shortDesc,
  115. longDesc=longDesc, hints=hints)
  116. def coerce(self, val):
  117. result = Integer.coerce(self, val)
  118. if self.allowNone and result == None:
  119. return result
  120. if result < self.min:
  121. raise InputError("Value %s is too small, it should be at least %s" % (result, self.min))
  122. if result > self.max:
  123. raise InputError("Value %s is too large, it should be at most %s" % (result, self.max))
  124. return result
  125. class Float(Argument):
  126. defaultDefault = None
  127. def __init__(self, name, allowNone=1, default=None, shortDesc=None,
  128. longDesc=None, hints=None):
  129. #although Argument now has allowNone, that was recently added, and
  130. #putting it at the end kept things which relied on argument order
  131. #from breaking. However, allowNone originally was in here, so
  132. #I have to keep the same order, to prevent breaking code that
  133. #depends on argument order only
  134. Argument.__init__(self, name, default, shortDesc, longDesc, hints,
  135. allowNone)
  136. def coerce(self, val):
  137. if not val.strip() and self.allowNone:
  138. return None
  139. try:
  140. return float(val)
  141. except ValueError:
  142. raise InputError("Invalid float: %s" % val)
  143. class Choice(Argument):
  144. """
  145. The result of a choice between enumerated types. The choices should
  146. be a list of tuples of tag, value, and description. The tag will be
  147. the value returned if the user hits "Submit", and the description
  148. is the bale for the enumerated type. default is a list of all the
  149. values (seconds element in choices). If no defaults are specified,
  150. initially the first item will be selected. Only one item can (should)
  151. be selected at once.
  152. """
  153. def __init__(self, name, choices=[], default=[], shortDesc=None,
  154. longDesc=None, hints=None, allowNone=1):
  155. self.choices = choices
  156. if choices and not default:
  157. default.append(choices[0][1])
  158. Argument.__init__(self, name, default, shortDesc, longDesc, hints, allowNone=allowNone)
  159. def coerce(self, inIdent):
  160. for ident, val, desc in self.choices:
  161. if ident == inIdent:
  162. return val
  163. else:
  164. raise InputError("Invalid Choice: %s" % inIdent)
  165. class Flags(Argument):
  166. """
  167. The result of a checkbox group or multi-menu. The flags should be a
  168. list of tuples of tag, value, and description. The tag will be
  169. the value returned if the user hits "Submit", and the description
  170. is the bale for the enumerated type. default is a list of all the
  171. values (second elements in flags). If no defaults are specified,
  172. initially nothing will be selected. Several items may be selected at
  173. once.
  174. """
  175. def __init__(self, name, flags=(), default=(), shortDesc=None,
  176. longDesc=None, hints=None, allowNone=1):
  177. self.flags = flags
  178. Argument.__init__(self, name, default, shortDesc, longDesc, hints, allowNone=allowNone)
  179. def coerce(self, inFlagKeys):
  180. if not inFlagKeys:
  181. return []
  182. outFlags = []
  183. for inFlagKey in inFlagKeys:
  184. for flagKey, flagVal, flagDesc in self.flags:
  185. if inFlagKey == flagKey:
  186. outFlags.append(flagVal)
  187. break
  188. else:
  189. raise InputError("Invalid Flag: %s" % inFlagKey)
  190. return outFlags
  191. class CheckGroup(Flags):
  192. pass
  193. class RadioGroup(Choice):
  194. pass
  195. class Boolean(Argument):
  196. def coerce(self, inVal):
  197. if not inVal:
  198. return 0
  199. lInVal = str(inVal).lower()
  200. if lInVal in ('no', 'n', 'f', 'false', '0'):
  201. return 0
  202. return 1
  203. class File(Argument):
  204. def __init__(self, name, allowNone=1, shortDesc=None, longDesc=None,
  205. hints=None):
  206. Argument.__init__(self, name, None, shortDesc, longDesc, hints,
  207. allowNone=allowNone)
  208. def coerce(self, file):
  209. if not file and self.allowNone:
  210. return None
  211. elif file:
  212. return file
  213. else:
  214. raise InputError("Invalid File")
  215. def positiveInt(x):
  216. x = int(x)
  217. if x <= 0: raise ValueError
  218. return x
  219. class Date(Argument):
  220. """A date -- (year, month, day) tuple."""
  221. defaultDefault = None
  222. def __init__(self, name, allowNone=1, default=None, shortDesc=None,
  223. longDesc=None, hints=None):
  224. Argument.__init__(self, name, default, shortDesc, longDesc, hints)
  225. self.allowNone = allowNone
  226. if not allowNone:
  227. self.defaultDefault = (1970, 1, 1)
  228. def coerce(self, args):
  229. """Return tuple of ints (year, month, day)."""
  230. if tuple(args) == ("", "", "") and self.allowNone:
  231. return None
  232. try:
  233. year, month, day = map(positiveInt, args)
  234. except ValueError:
  235. raise InputError("Invalid date")
  236. if (month, day) == (2, 29):
  237. if not calendar.isleap(year):
  238. raise InputError("%d was not a leap year" % year)
  239. else:
  240. return year, month, day
  241. try:
  242. mdays = calendar.mdays[month]
  243. except IndexError:
  244. raise InputError("Invalid date")
  245. if day > mdays:
  246. raise InputError("Invalid date")
  247. return year, month, day
  248. class Submit(Choice):
  249. """Submit button or a reasonable facsimile thereof."""
  250. def __init__(self, name, choices=[("Submit", "submit", "Submit form")],
  251. reset=0, shortDesc=None, longDesc=None, allowNone=0, hints=None):
  252. Choice.__init__(self, name, choices=choices, shortDesc=shortDesc,
  253. longDesc=longDesc, hints=hints)
  254. self.allowNone = allowNone
  255. self.reset = reset
  256. def coerce(self, value):
  257. if self.allowNone and not value:
  258. return None
  259. else:
  260. return Choice.coerce(self, value)
  261. @_oldStyle
  262. class PresentationHint:
  263. """
  264. A hint to a particular system.
  265. """
  266. @_oldStyle
  267. class MethodSignature:
  268. """
  269. A signature of a callable.
  270. """
  271. def __init__(self, *sigList):
  272. """
  273. """
  274. self.methodSignature = sigList
  275. def getArgument(self, name):
  276. for a in self.methodSignature:
  277. if a.name == name:
  278. return a
  279. def method(self, callable, takesRequest=False):
  280. return FormMethod(self, callable, takesRequest)
  281. @_oldStyle
  282. class FormMethod:
  283. """A callable object with a signature."""
  284. def __init__(self, signature, callable, takesRequest=False):
  285. self.signature = signature
  286. self.callable = callable
  287. self.takesRequest = takesRequest
  288. def getArgs(self):
  289. return tuple(self.signature.methodSignature)
  290. def call(self,*args,**kw):
  291. return self.callable(*args,**kw)