Werkzeug

Management Script Utilities

Most of the time you have recurring tasks while writing an application such as starting up an interactive python interpreter with some prefilled imports, starting the development server, initializing the database or something similar.

For that purpose werkzeug provides the werkzeug.script module which helps you writing such scripts.

Basic Usage

The following snippet is roughly the same in every werkzeug script:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from werkzeug import script

# actions go here

if __name__ == '__main__':
    script.run()

Starting this script now does nothing because no actions are defined. An action is a function in the same module starting with "action_" which takes a number of arguments where every argument has a default. The type of the default value specifies the type of the argument.

Arguments can then be passed by position or using --name=value from the shell.

Because a runserver and shell command is pretty common there are two factory functions that create such commands:

def make_app():
    from yourapplication import YourApplication
    return YourApplication(...)

action_runserver = script.make_runserver(make_app, use_reloader=True)
action_shell = script.make_shell(lambda: {'app': make_app()})

Using The Scripts

The script from above can be used like this from the shell now:

$ ./manage.py --help
$ ./manage.py runserver localhost 8080 --debugger --no-reloader
$ ./manage.py runserver -p 4000
$ ./manage.py shell

As you can see it’s possible to pass parameters as positional arguments or as named parameters, pretty much like Python function calls.

Writing Actions

Writing new action functions is pretty straightforward. All you have to do is to name the function action_COMMAND and it will be available as ./manage.py COMMAND. The docstring of the function is used for the help screen and all arguments must have defaults which the run function can inspect. As a matter of fact you cannot use *args or **kwargs constructs.

An additional feature is the definition of tuples as defaults. The first item in the tuple could be a short name for the command and the second the default value:

def action_add_user(username=('u', ''), password=('p', '')):
    """Docstring goes here."""
    ...

Action Discovery

Per default, the run function looks up variables in the current locals. That means if no arguments are provided, it implicitly assumes this call:

script.run(locals(), 'action_')

If you don’t want to use an action discovery, you can set the prefix to an empty string and pass a dict with functions:

script.run(dict(
    runserver=script.make_runserver(make_app, use_reloader=True),
    shell=script.make_shell(lambda: {'app': make_app()}),
    initdb=on_initdb
), '')

Reference

werkzeug.script.run(namespace=None, action_prefix='action_', args=None)

Run the script. Participating actions are looked up in the callers namespace if no namespace is given, otherwise in the dict provided. Only items that start with action_prefix are processed as actions. If you want to use all items in the namespace provided as actions set action_prefix to an empty string.

Parameters:
  • namespace – An optional dict where the functions are looked up in. By default the local namespace of the caller is used.
  • action_prefix – The prefix for the functions. Everything else is ignored.
  • args – the arguments for the function. If not specified sys.argv without the first argument is used.
werkzeug.script.make_shell(init_func=None, banner=None, use_ipython=True)

Returns an action callback that spawns a new interactive python shell.

Parameters:
  • init_func – an optional initialization function that is called before the shell is started. The return value of this function is the initial namespace.
  • banner – the banner that is displayed before the shell. If not specified a generic banner is used instead.
  • use_ipython – if set to True ipython is used if available.
werkzeug.script.make_runserver(app_factory, hostname='localhost', port=5000, use_reloader=False, use_debugger=False, use_evalex=True, threaded=False, processes=1, static_files=None)

Returns an action callback that spawns a new development server.

New in version 0.5: static_files was added.

Parameters:
  • app_factory – a function that returns a new WSGI application.
  • hostname – the default hostname the server should listen on.
  • port – the default port of the server.
  • use_reloader – the default setting for the reloader.
  • use_evalex – the default setting for the evalex flag of the debugger.
  • threaded – the default threading setting.
  • processes – the default number of processes to start.
  • static_files – optionally a dict of static files.

Example Scripts

In the Werkzeug example folder there are some ./manage-APP.py scripts using werkzeug.script.