Howdy!

I usually use the class dispatching mechanism that instantiates some class for a matching request and calls a method depending on the request method (GET or POST or HEAD). In these instances I usually want to use a db connection, service, auth manager or whatever.

From my own personal fork of Web.py (http://github.com/GothAlice/ webpy/) I've introduced more literal object/method dispatch (without the distinction between get, post, head, etc.) which can be seen illustrated on the following Wiki page: http://wiki.github.com/GothAlice/webpy/object-dispatch-example .

My question is, how one would inject those dependencies into the generated instances.

For the most part I use the add_processor extension method to add pre/ post request hooks to my code. As an example, from the Web.py cookbook article on adding SQLAlchemy ORM support, I've used the following in my code to automatically handle database sessions:

        def load_sqlalchemy(handler):
            web.ctx.orm = scoped_session(sessionmaker(bind=engine))
            try:
                return handler()
            except web.HTTPError:
               web.ctx.orm.commit()
               raise
            except:
                web.ctx.orm.rollback()
                raise
            finally:
                web.ctx.orm.commit()
        
        # ...
        app.add_processor(load_sqlalchemy)

I surely know several ways around this problem, which mostly include global variables of sorts (globals, registries or whatever), but they all do not seem very elegant.

So how would you go about injecting dependencies into your handler instances (or don't you?)?


For my object dispatch mechanism, I can add common hooks to the Controller or dispatch classes in:

http://github.com/GothAlice/webpy/blob/e38220855012f274dfe23d512c2cdba063eaa581/web/extras/dispatch.py

But the add_processor method seems to be the most useful. As another example, I've added simplified template usage to my fork as well:

http://wiki.github.com/GothAlice/webpy/object-dispatch-using-templates-example

        — Alice.

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to