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.

318 lines
11 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. r'''
  3. werkzeug.script
  4. ~~~~~~~~~~~~~~~
  5. .. admonition:: Deprecated Functionality
  6. ``werkzeug.script`` is deprecated without replacement functionality.
  7. Python's command line support improved greatly with :mod:`argparse`
  8. and a bunch of alternative modules.
  9. Most of the time you have recurring tasks while writing an application
  10. such as starting up an interactive python interpreter with some prefilled
  11. imports, starting the development server, initializing the database or
  12. something similar.
  13. For that purpose werkzeug provides the `werkzeug.script` module which
  14. helps you writing such scripts.
  15. Basic Usage
  16. -----------
  17. The following snippet is roughly the same in every werkzeug script::
  18. #!/usr/bin/env python
  19. # -*- coding: utf-8 -*-
  20. from werkzeug import script
  21. # actions go here
  22. if __name__ == '__main__':
  23. script.run()
  24. Starting this script now does nothing because no actions are defined.
  25. An action is a function in the same module starting with ``"action_"``
  26. which takes a number of arguments where every argument has a default. The
  27. type of the default value specifies the type of the argument.
  28. Arguments can then be passed by position or using ``--name=value`` from
  29. the shell.
  30. Because a runserver and shell command is pretty common there are two
  31. factory functions that create such commands::
  32. def make_app():
  33. from yourapplication import YourApplication
  34. return YourApplication(...)
  35. action_runserver = script.make_runserver(make_app, use_reloader=True)
  36. action_shell = script.make_shell(lambda: {'app': make_app()})
  37. Using The Scripts
  38. -----------------
  39. The script from above can be used like this from the shell now:
  40. .. sourcecode:: text
  41. $ ./manage.py --help
  42. $ ./manage.py runserver localhost 8080 --debugger --no-reloader
  43. $ ./manage.py runserver -p 4000
  44. $ ./manage.py shell
  45. As you can see it's possible to pass parameters as positional arguments
  46. or as named parameters, pretty much like Python function calls.
  47. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  48. :license: BSD, see LICENSE for more details.
  49. '''
  50. from __future__ import print_function
  51. import sys
  52. import inspect
  53. import getopt
  54. from os.path import basename
  55. from werkzeug._compat import iteritems
  56. argument_types = {
  57. bool: 'boolean',
  58. str: 'string',
  59. int: 'integer',
  60. float: 'float'
  61. }
  62. converters = {
  63. 'boolean': lambda x: x.lower() in ('1', 'true', 'yes', 'on'),
  64. 'string': str,
  65. 'integer': int,
  66. 'float': float
  67. }
  68. def run(namespace=None, action_prefix='action_', args=None):
  69. """Run the script. Participating actions are looked up in the caller's
  70. namespace if no namespace is given, otherwise in the dict provided.
  71. Only items that start with action_prefix are processed as actions. If
  72. you want to use all items in the namespace provided as actions set
  73. action_prefix to an empty string.
  74. :param namespace: An optional dict where the functions are looked up in.
  75. By default the local namespace of the caller is used.
  76. :param action_prefix: The prefix for the functions. Everything else
  77. is ignored.
  78. :param args: the arguments for the function. If not specified
  79. :data:`sys.argv` without the first argument is used.
  80. """
  81. if namespace is None:
  82. namespace = sys._getframe(1).f_locals
  83. actions = find_actions(namespace, action_prefix)
  84. if args is None:
  85. args = sys.argv[1:]
  86. if not args or args[0] in ('-h', '--help'):
  87. return print_usage(actions)
  88. elif args[0] not in actions:
  89. fail('Unknown action \'%s\'' % args[0])
  90. arguments = {}
  91. types = {}
  92. key_to_arg = {}
  93. long_options = []
  94. formatstring = ''
  95. func, doc, arg_def = actions[args.pop(0)]
  96. for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):
  97. real_arg = arg.replace('-', '_')
  98. if shortcut:
  99. formatstring += shortcut
  100. if not isinstance(default, bool):
  101. formatstring += ':'
  102. key_to_arg['-' + shortcut] = real_arg
  103. long_options.append(isinstance(default, bool) and arg or arg + '=')
  104. key_to_arg['--' + arg] = real_arg
  105. key_to_arg[idx] = real_arg
  106. types[real_arg] = option_type
  107. arguments[real_arg] = default
  108. try:
  109. optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)
  110. except getopt.GetoptError as e:
  111. fail(str(e))
  112. specified_arguments = set()
  113. for key, value in enumerate(posargs):
  114. try:
  115. arg = key_to_arg[key]
  116. except IndexError:
  117. fail('Too many parameters')
  118. specified_arguments.add(arg)
  119. try:
  120. arguments[arg] = converters[types[arg]](value)
  121. except ValueError:
  122. fail('Invalid value for argument %s (%s): %s' % (key, arg, value))
  123. for key, value in optlist:
  124. arg = key_to_arg[key]
  125. if arg in specified_arguments:
  126. fail('Argument \'%s\' is specified twice' % arg)
  127. if types[arg] == 'boolean':
  128. if arg.startswith('no_'):
  129. value = 'no'
  130. else:
  131. value = 'yes'
  132. try:
  133. arguments[arg] = converters[types[arg]](value)
  134. except ValueError:
  135. fail('Invalid value for \'%s\': %s' % (key, value))
  136. newargs = {}
  137. for k, v in iteritems(arguments):
  138. newargs[k.startswith('no_') and k[3:] or k] = v
  139. arguments = newargs
  140. return func(**arguments)
  141. def fail(message, code=-1):
  142. """Fail with an error."""
  143. print('Error: %s' % message, file=sys.stderr)
  144. sys.exit(code)
  145. def find_actions(namespace, action_prefix):
  146. """Find all the actions in the namespace."""
  147. actions = {}
  148. for key, value in iteritems(namespace):
  149. if key.startswith(action_prefix):
  150. actions[key[len(action_prefix):]] = analyse_action(value)
  151. return actions
  152. def print_usage(actions):
  153. """Print the usage information. (Help screen)"""
  154. actions = sorted(iteritems(actions))
  155. print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
  156. print(' %s --help' % basename(sys.argv[0]))
  157. print()
  158. print('actions:')
  159. for name, (func, doc, arguments) in actions:
  160. print(' %s:' % name)
  161. for line in doc.splitlines():
  162. print(' %s' % line)
  163. if arguments:
  164. print()
  165. for arg, shortcut, default, argtype in arguments:
  166. if isinstance(default, bool):
  167. print(' %s' % (
  168. (shortcut and '-%s, ' % shortcut or '') + '--' + arg
  169. ))
  170. else:
  171. print(' %-30s%-10s%s' % (
  172. (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
  173. argtype, default
  174. ))
  175. print()
  176. def analyse_action(func):
  177. """Analyse a function."""
  178. description = inspect.getdoc(func) or 'undocumented action'
  179. arguments = []
  180. args, varargs, kwargs, defaults = inspect.getargspec(func)
  181. if varargs or kwargs:
  182. raise TypeError('variable length arguments for action not allowed.')
  183. if len(args) != len(defaults or ()):
  184. raise TypeError('not all arguments have proper definitions')
  185. for idx, (arg, definition) in enumerate(zip(args, defaults or ())):
  186. if arg.startswith('_'):
  187. raise TypeError('arguments may not start with an underscore')
  188. if not isinstance(definition, tuple):
  189. shortcut = None
  190. default = definition
  191. else:
  192. shortcut, default = definition
  193. argument_type = argument_types[type(default)]
  194. if isinstance(default, bool) and default is True:
  195. arg = 'no-' + arg
  196. arguments.append((arg.replace('_', '-'), shortcut,
  197. default, argument_type))
  198. return func, description, arguments
  199. def make_shell(init_func=None, banner=None, use_ipython=True):
  200. """Returns an action callback that spawns a new interactive
  201. python shell.
  202. :param init_func: an optional initialization function that is
  203. called before the shell is started. The return
  204. value of this function is the initial namespace.
  205. :param banner: the banner that is displayed before the shell. If
  206. not specified a generic banner is used instead.
  207. :param use_ipython: if set to `True` ipython is used if available.
  208. """
  209. if banner is None:
  210. banner = 'Interactive Werkzeug Shell'
  211. if init_func is None:
  212. init_func = dict
  213. def action(ipython=use_ipython):
  214. """Start a new interactive python session."""
  215. namespace = init_func()
  216. if ipython:
  217. try:
  218. try:
  219. from IPython.frontend.terminal.embed import InteractiveShellEmbed
  220. sh = InteractiveShellEmbed(banner1=banner)
  221. except ImportError:
  222. from IPython.Shell import IPShellEmbed
  223. sh = IPShellEmbed(banner=banner)
  224. except ImportError:
  225. pass
  226. else:
  227. sh(global_ns={}, local_ns=namespace)
  228. return
  229. from code import interact
  230. interact(banner, local=namespace)
  231. return action
  232. def make_runserver(app_factory, hostname='localhost', port=5000,
  233. use_reloader=False, use_debugger=False, use_evalex=True,
  234. threaded=False, processes=1, static_files=None,
  235. extra_files=None, ssl_context=None):
  236. """Returns an action callback that spawns a new development server.
  237. .. versionadded:: 0.5
  238. `static_files` and `extra_files` was added.
  239. ..versionadded:: 0.6.1
  240. `ssl_context` was added.
  241. :param app_factory: a function that returns a new WSGI application.
  242. :param hostname: the default hostname the server should listen on.
  243. :param port: the default port of the server.
  244. :param use_reloader: the default setting for the reloader.
  245. :param use_evalex: the default setting for the evalex flag of the debugger.
  246. :param threaded: the default threading setting.
  247. :param processes: the default number of processes to start.
  248. :param static_files: optional dict of static files.
  249. :param extra_files: optional list of extra files to track for reloading.
  250. :param ssl_context: optional SSL context for running server in HTTPS mode.
  251. """
  252. def action(hostname=('h', hostname), port=('p', port),
  253. reloader=use_reloader, debugger=use_debugger,
  254. evalex=use_evalex, threaded=threaded, processes=processes):
  255. """Start a new development server."""
  256. from werkzeug.serving import run_simple
  257. app = app_factory()
  258. run_simple(hostname, port, app,
  259. use_reloader=reloader, use_debugger=debugger,
  260. use_evalex=evalex, extra_files=extra_files,
  261. reloader_interval=1, threaded=threaded, processes=processes,
  262. static_files=static_files, ssl_context=ssl_context)
  263. return action