class some_url_handler:
def GET(self):
from globals import *
some_template_specific_variable = "some value"
...
web.render('some.tmpl')
The drawback is that i have to do the "from globals import *" for each
url handler. Any ideas?
Cheers,
--
Soni Bergraj
First, you probably don't want to use globals for your module, because
that's the name of a built-in function.
That said, one idea that comes to mind is inheritance:
globvars = {'variable1':'value1', 'variable2':'value2'}
class useglobals:
def __init__(self):
for k, v in globvars.iteritems():
setattr(self, k, v)
class some_url_handler(useglobals):
def GET(self):
some_specific_variable = "some value"
web.render('some.templ')
Actually, now that I think about it, that won't work properly, since
attributes aren't local variables. I'll reply with a working example
once I get one.
First, you need to decide if you want the global variables to be in
their own namespace. That is, if you have a global variable named
'sitename', do you want to access it with $sitename or
$globvars.sitename in your template. I recommend using a separate
namespace, but that's up to you.
In request(), at or around line 1262, you'll see these lines:
elif terms is None:
terms = {'context': context}
terms.update(sys._getframe(1).f_locals)
Immediately below them add one of the following.
If you want the global variables to have their own namespace, add:
if hasattr(terms['self'], 'globvars'):
terms['globvars'] = terms['self'].globvars
If you want the global variables to be in the same namespace as the
local variables, add:
if hasattr(terms['self'], 'globvars'):
for k in terms['self'].globvars:
terms[k] = terms['self'].globvars[k]
Then, in your code, you'll need to do something like the following,
which is very similar to the previous code I posted:
globvars = web.Storage({'variable1':'value1', 'variable2':'value2'})
class useglobvars:
def __init__(self):
self.globvars = globvars
class some_url_handler(useglobvars):
def GET(self):
some_specific_variable = "some value"
web.render('temp.html')
I tested this and it does work, but maybe someone has an idea that
doesn't involve editing web.py.
You should probably do something like:
web.render('some.tmpl', web.dictsum(locals(), globals()))
I, uh, can't find dictsum in the version of web.py on the site. (0.135)
Oops, I meand dictadd.
Sometimes it requires you to read the code & make a bit of a leap. Just
check the closest method names & read what the code is doing. The
function sigs are here <http://webpy.org/documentation> .