[twill] Need help with a run_on_page_load function
Matthew Wilson
matt at tplus1.com
Thu Feb 14 11:07:37 PST 2008
I really like the require extension, but when I looked inside, I didn't
see an obvious way to extend it to allow me to run any arbritary code at
every page load.
So I wrote this run_on_page_load function:
def run_on_page_load(funcname):
"Run the function named funcname on every page load."
try:
f = globals()[funcname]
except KeyError:
parent_frame = inspect.currentframe(1)
f = parent_frame.f_locals[funcname]
# Now make a new function that discards the args passed in.
def g(*args, **kwargs):
return f()
g.func_name = funcname
# Add g to the post load hooks as long as it ain't already in there.
b = get_browser()
if not [x for x in b._post_load_hooks if x.func_name == funcname]:
b._post_load_hooks.append(g)
Here's a simple demonstration:
def show_if_500():
"Dump out the HTML for the page if it returns a 500."
b = get_browser()
if b.get_code() == 500:
show()
raise TwillAssertionError("Page %s returned a 500 status!"
% b.get_url())
# This will execute show_if_500 on every page.
run_on_page_load(show_if_500.func_name)
I pass in the name name of the function rather than the function itself
because when I run the twill shell, any argument that I give my
run_on_page_load function are just passed in as strings:
$ twill-sh
-= Welcome to twill! =-
current page: *empty page*
>> extend_with tweed
Imported extension module 'tweed'.
(at /home/matt/svn-checkouts/tweed/tweed/__init__.pyc)
Description:
Some twill-related nonsense.
current page: *empty page*
>> run_on_page_load show_if_500
current page: *empty page*
I don't know anything about how the parsing part of twill works. Is
there a better way to implement run_on_page_load?
Matt
--
Programming, economics, gardening, life in Cleveland.
http://blog.tplus1.com
More information about the twill
mailing list