web.py: avoid global instances?
the last few weaks, I am playing a little bit with the Web.py framework.
As my application is now getting bigger and bigger, I want to restructure
the sourcecode and put code fragments in different classes. Now, I don't
really know where I should create my object instances if I need them in
different web.py classes. Let us assume, my sourcecode looks like:
import web
import myclass
urls = (
'/', 'index',
'/test', 'test'
)
#should i make my instance global...
my = myclass.myClass()
class test:
def __init__(self):
#...or should i make my instance local: my = myclass.myClass()
pass
def GET(self):
item = my.getItem()
return item
def POST(self):
pass
class index:
def __init__(self):
#...or should i make my instance local: my = myclass.myClass()
pass
def GET(self):
date = my.getDate()
return date
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
Now, I want to access the methods getItem() and getDate() (which belong to
the instance my), if the appropriate sites in my webbrowser are called. My
question is now: Should I make the instance global or is it better, if I
make it local? I really don't like global instances, but I don't see any
other way as to make it global. Sure, it would be possible, to create a
local instance, but then, every time the page loads, a new instance would
be created, right? Normally, this wouldn't be a problem, but myclass
accesses a serial port, so I need to make sure, that only one instance is
created.
Am I missing something or is a global instance the only possible solution
to accomplish this?
No comments:
Post a Comment