I think I've gotten my script.py module down to an artform. This
allows me to write first-class scripts that do minimal startup.
Here's how I use it:
#!/usr/bin/env python
# Import all my model and such
from pylons import config
# You can import other things, such as url and even tmpl_context
from myapp.script import init
def main():
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("must provide config file")
ini = args[0];
import os.path
ini = os.path.abspath(ini)
if options.verbose:
print "Initializing with %r" % ini
init(ini)
Here's what script.py like:
from paste.deploy import appconfig
import paste.registry
from myapp.config.environment import load_environment
from pylons.i18n.translation import _get_translator
from pylons.util import PylonsContext, ContextObj
from routes.util import URLGenerator
from pylons import config
import pylons
class Request(object):
def __init__(self):
self.environ = dict()
def init(config_filename):
if config_filename[0] != '/':
# Needs to be an absolute path
from os.path import abspath
config_filename = abspath(config_filename)
cfg = appconfig("config:"+config_filename)
load_environment(cfg.global_conf, cfg.local_conf)
registry = paste.registry.Registry()
registry.prepare()
registry.register(pylons.url, URLGenerator(config['routes.map'],
{'HTTP_HOST':config['host']}))
registry.register(pylons.tmpl_context, ContextObj())
registry.register(pylons.request, Request())
registry.register(pylons.response, None)
config.setdefault('lang', None)
registry.register(pylons.translator, _get_translator(config['lang'],
pylons_config=config))
I know there've been a lot of different recommendations for setting up
the Pylons environment outside of a Pylons request. In my case, I use
it for access to the DB through the model, generating URLs the same
way I do inside the environment, and even rendering templates for
things like sending email. (That's an interesting module I should
share as well.)
I wanted to hear what your guys opinion of what I've been spending my
time on over the past several months is. Maybe someone will find this
useful. If it is generally useful, should I put it up somewhere where
we can collaborate?
--
Jonathan Gardner
[email protected]
--
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en.