On Jul 6, 2011, at 1:23 AM, Miguel Lopes wrote:
> I'm experimenting with dynamically generating functions, aka 'actions' in 
> controllers. However, I've been unsuccessful. I can use exec and closures 
> successfully in regular Python code, but I can't make it work with web2py. 
> Any thoughts on how to achieve this?

web2py finds functions by reading the (static) controller file itself. See 
gluon.compileapp.run_controller_in, in particular this line:

        exposed = regex_expose.findall(code)

So, no dynamically generated controller actions, at least not directly.

I haven't given this much thought, but one way you might accomplish the same 
effect would be to push the dynamic function name down one level in the URL, 
something like: http://domain.com/app/dynamic/index/function/...

...where 'dynamic' is the controller with dynamic functions, and index is a 
(static) function that calls function dynamically. You might optimize the 
lookup function to extract only the one desired function from your page table.

Depending on your overall URL structure, you could rewrite the URLs to shorten 
them up.

> 
> A closure example - FAILS in web2py:
> top_pages = db(db.page.id > 0).select()
> def add_actions(top_pages):
>     for page in top_pages:
>         def inneraction(msg):
>             sidebar = None
>             return dict(message=msg, sidebar=sidebar)
>         inneraction.__name__ = page.link_name
>         globals()[page.link_name] = inneraction
> 
> add_actions(top_pages)
> 
> A exec example - FAILS in web2py:
> ACTION_TEMPLATE = """
>  def NEW_ACTION():
>     sidebar = None
>     return dict(message='s', sidebar=sidebar)
>  """
> top_pages = db(db.page.id > 0).select()
> def makePages(pages):
>     for page in top_pages:
>         exec ACTION_TEMPLATE
>         NEW_ACTION.__name__ = page.link_name
>         globals()[page.link_name] = NEW_ACTION
> 
> makePages(pages)
> 
> Miguel
> 


Reply via email to