tags:

views:

687

answers:

2

I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.

How can I launch a controller as a stand alone script?

I currently have:

from warehouse2.controllers import importServer
importServer.runServer(60)

and in the controller file, but not part of the controller class:

def runServer(sleep_secs):
    try:
        imp = ImportserverController()
        while(True):
            imp.runImport()
            sleepFor(sleep_secs)

    except Exception, e:
        log.info("Unexpected error: %s" % sys.exc_info()[0])
        log.info(e)

But starting ImportServer.py on the command line results in:

2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I
mportJob|n_imports, SQL expression or this Session
+1  A: 

I'm redacting my response and upvoting the other answer by Ben Bangert, as it's the correct one. I answered and have since learned the correct way (mentioned below). If you really want to, check out the history of this answer to see the wrong (but working) solution I originally proposed.

Douglas Mayle
Yeah, I couldn't figure out how to load all of the stuff that paster does. Your solution nicely sidesteps that. Thanks.
JohnLavoie
cat'ing a script to paster shell scares me. The interactive Python shell has different rules for, e.g. terminating multi-line statements.
Marius Gedminas
Marius, take a look at Ben's answer below. He's the authoritative resource when it comes to thinks like pylons, since I answered this, I figured out how to do the same correctly.
Douglas Mayle
+5  A: 

If you want to load parts of a Pylons app, such as the models from outside Pylons, load the Pylons app in the script first:

from paste.deploy import appconfig
from pylons import config

from YOURPROJ.config.environment import load_environment

conf = appconfig('config:development.ini', relative_to='.')
load_environment(conf.global_conf, conf.local_conf)

That will load the Pylons app, which sets up most of the state so that you can proceed to use the SQLAlchemy models and Session to work with the database.

Note that if your code is using the pylons globals such as request/response/etc then that won't work since they require a request to be in progress to exist.

Ben Bangert