Package: gearbox
About gearboxGearbox is a paster command replacement for TurboGears2.
It has been created during the process of providing Python3 support to the TurboGears2 web framework,
while still being backward compatible with the existing TurboGears projects.Gearbox is based on a stripped down version ofCliffcommand line framework, you might want
to considerClifffor more advanced use cases
and custom command interpreters.Installinggearbox can be installed from pypi:pip install gearboxshould just work for most of the usersOut of The BoxJust by installing gearbox itself your TurboGears project will be able to use gearbox system wide
commands likegearbox serve,gearboxsetup-appandgearbox makepackagecommands.
These commands provide a replacement for the paster serve, paster setup-app and paster create commands.The main difference with the paster command is usually only that gearbox commands explicitly set the
configuration file using the--configoption instead of accepting it positionally.  By default gearbox
will always load a configuration file nameddevelopment.ini, this mean you can simply rungearbox servein place ofpaster serve development.iniTo have a list of the available commands simply rungearbox--help:$ gearbox --help
usage: gearbox [--version] [-v] [--log-file LOG_FILE] [-q] [-h] [--debug]

TurboGears2 Gearbox toolset

optional arguments:
  --version            show program's version number and exit
  -v, --verbose        Increase verbosity of output. Can be repeated.
  --log-file LOG_FILE  Specify a file to log output. Disabled by default.
  -q, --quiet          suppress output except warnings and errors
  -h, --help           show this help message and exit
  --debug              show tracebacks on errors

Commands:
  help           print detailed help for another command
  makepackage    Creates a basic python package
  migrate        Handles TurboGears2 Database Migrations
  quickstart     Creates a new TurboGears2 project
  serve          Serves a web application that uses a PasteDeploy configuration file
  setup-app      Setup an application, given a config file
  tgshell        Opens an interactive shell with a TurboGears2 app loaded
  scaffold       Creates a new file from a scaffold templateThen it is possible to ask for help for a given command by usinggearbox help command:$ gearbox help serve
usage: gearbox serve [-h] [-n NAME] [-s SERVER_TYPE]
                     [--server-name SECTION_NAME] [--daemon]
                     [--pid-file FILENAME] [--reload]
                     [--reload-interval RELOAD_INTERVAL] [--monitor-restart]
                     [--status] [--user USERNAME] [--group GROUP]
                     [--stop-daemon] [-c CONFIG_FILE]
                     [args [args ...]]

Serves a web application that uses a PasteDeploy configuration file

positional arguments:
  args

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --app-name NAME
                        Load the named application (default main)
  -s SERVER_TYPE, --server SERVER_TYPE
                        Use the named server.
  --server-name SECTION_NAME
                        Use the named server as defined in the configuration
                        file (default: main)
  --daemon              Run in daemon (background) mode
  --pid-file FILENAME   Save PID to file (default to gearbox.pid if running in
                        daemon mode)
  --reload              Use auto-restart file monitor
  --reload-interval RELOAD_INTERVAL
                        Seconds between checking files (low number can cause
                        significant CPU usage)
  --monitor-restart     Auto-restart server if it dies
  --status              Show the status of the (presumably daemonized) server
  --user USERNAME       Set the user (usually only possible when run as root)
  --group GROUP         Set the group (usually only possible when run as root)
  --stop-daemon         Stop a daemonized server (given a PID file, or default
                        gearbox.pid file)
  -c CONFIG_FILE, --config CONFIG_FILE
                        application config file to read (default:
                        development.ini)Development Tools CommandsInstalling the TurboGears 2.3 development tools you will get access some some gearbox commands specific
to TurboGears2 projects management, those are thegearbox quickstart,gearbox tgshellandgearbox migratecommands.While thequickstartcommand will be automatically available, you will have to enable project scope plugins
for gearbox before the other two became available. This will let gearbox know that you are running it inside
a TurboGears2 project and so that the commands that only make sense for TurboGears2 projects will became available.Enabling migrate and tgshell commandsTo enablegearbox migrateandgearbox tgshellcommands make sure that yoursetup.pyentry_pointslook like:entry_points={
    'paste.app_factory': [
        'main = makonoauth.config.middleware:make_app'
    ],
    'gearbox.plugins': [
        'turbogears-devtools = tg.devtools'
    ]
}Thepaste.app_factorysection will letgearbox serveknow how to create the application that
has to be served. Gearbox relies on PasteDeploy for application setup, so it required a paste.app_factory
section to be able to correctly load the application.While thegearbox.pluginssection will letgearboxitself know that inside that directory the tg.devtools
commands have to be enabled makinggearbox tgshellandgearbox migrateavailable when we run gearbox
from inside our project directory.Gearbox Interactive ModeBy default launching gearbox without any subcommand will start the interactive mode.
This provides an interactive prompt where gearbox commands, system shell commands and python statements
can be executed. If you have any doubt about what you can do simply run thehelpcommand to get
a list of the commands available (runninghelp somecommandwill provide help for the given sub command).Gearbox HTTP ServersIf you are moving your TurboGears2 project from paster you will probably end serving your
application with Paste HTTP server even if you are using thegearbox servecommand.The reason for this behavior is that gearbox is going to use what is specified inside
theserver:mainsection of your.inifile to serve your application.
TurboGears2 projects quickstarted before 2.3 used Paste and so the projects is probably
configured to use Paste#http as the server. This is not an issue by itself, it will just require
you to have Paste installed to be able to serve the application, to totally remove the Paste
dependency simply replacePaste#httpwithgearbox#wsgiref.Thegearbox#wsgirefalso supports an experimental multithreaded version that
can be enabled by setting thewsgiref.threaded = trueoption in your server
configuration section.Serving with GEventGearbox cames with builtin support for gevent, so serving an application under Gevent
is just a matter of usinggearbox#geventas your server inside theserver:mainsection
of the configuration file.The gearbox gevent server will automatically monkeypatch all the python modules apart
from the DNS related functions before loading your application.
Not much more apart making sure that your code is gevent compatible is required.ScaffoldingScaffolding is the process of creating a new component of your web application
through a template or preset.Thegearbox scaffoldcommand permits to create new files from scaffolds (file templates)
which you can place inside your project itself. Scaffold files should be named with.templateextension and can be used by running:$ gearbox scaffold templatename targetThis will create atargetfile (do not provide the extension, that is specified inside
the templatename itself) starting from thetemplatenamescaffold.A tipical scaffold filename will be named likemodel.py.templateand will look like:class {{target.capitalize()}}(DeclarativeBase):
    __tablename__ = '{{target.lower()}}s'

    uid = Column(Integer, primary_key=True)
    data = Column(Unicode(255), nullable=False)Patchingpatchis one of the few builtin commands of Gearbox and is commonly used to
update code. You can think of it as an easier to used sed command mixed with python.Here are a few examples, this will replace all xi:include occurrences
with py:extends in all the template files recursively:$ gearbox patch -R '*.html' xi:include -r py:extendsIt is also possible to rely on regex and python for more complex
replacements, like updating the Copyright year in your documentation:$ gearbox patch -R '*.rst' -x 'Copyright(\s*)(\d+)' -e -r '"Copyright\\g<1>"+__import__("datetime").datetime.utcnow().strftime("%Y")'Please refer togearbox help patchfor available options.Writing new gearbox commandsGearbox will automatically load any command registered as a setuptools entry point withgearbox.commandskey. To create a new command you must subclass thegearbox.command.Commandclass, override theget_parserandtake_actionmethods to provide custom options and
a custom behaviour:class MyCcommand(Command):
    def take_action(self, opts):
        print('Hello World!')Then register your command in the setup.py entry points of your package:setup(name='mydistribution',
      entry_points={
         'gearbox.commands': [
             'mycommand = mypackage.commands:MyCommand',
         ]
      })Template Based CommandsWriting new gearbox template commands is as simple as creating agearbox.command.TemplateCommandsubclass and
place it inside acommand.pyfile in a python package.Inherit from the class and implement theget_description,get_parserandtake_actionmethods
as described by the  documentation.The only difference is that yourtake_actionmethod has to end by callingself.run_template(output_dir, opts)whereoutput_diris the directory where the template output has to be written andoptsare the command options
as your take_action method received them.When the run_template command is called Gearbox will automatically run thetemplatedirectory in the same package where the command was available.Each file ending with the_tmplsyntax will be processed with the Tempita template engine and
whenever the name of a file or directory contains+optname+it will be substituted with the
value of the option having the same name (e.g., +package+ will be substituted with the value
of the –package options which will probably end being the name of the package).