Reputation: 42053
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.
Upvotes: 1
Views: 375
Reputation: 410
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)
Upvotes: 1
Reputation: 11252
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.
Upvotes: 0