views:

91

answers:

2

I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary.

I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.:

class Central():

def __init__(self):

    engine = engine_from_config(config, 'sqlalchemy.central.')     
    central_db = create_engine(engine)

    print central_db

However this doesn't work when I call:

c = DBConnect.Central()

What is the proper code for doing this?

Thanks.

A: 

Can you define "doesn't work"?

If you want to use central_db and engine later, you need to store them in the object (use self.central_db, self.engine, you can later access them as c.central_db and c.engine). Now they're just local variables which are destroyed once your constructor is finished.

Wim
I get bombarded with all sorts of errors. When I implement what you suggest, I'm thrown a:NameError: global name 'engine' is not defined
ensnare
If I change everything to self. I get:AttributeError: 'Engine' object has no attribute 'get_dialect'
ensnare
+1  A: 

Hi

Since I can't tell what's the layout of your code, I can only assume that you've got engine and central_db defined somewhere in the global context. Is that correct? If so you could try something like this:

def __init__(self):
    global engine
    global central_db
    engine = engine_from_config(config, 'sqlalchemy.central.')     
    central_db = create_engine(engine)

It will reference global engine and central_db objects instead of local ones (as Wim described)

Dave