Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

formmethod.py 12KB

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