whi
whi

Reputation: 2750

how to list all available url usage in web.py

urls = ( 'foo','foo','bar','bar', '/', index)

I want to list all available urls if visit / path. Any auto method?

Upvotes: 0

Views: 106

Answers (1)

pbuck
pbuck

Reputation: 4551

web.py uses the even-numbered elements to describe the path, and the odd-numbered elements to provide the url handler. That's why it's commonly written as:

urls = ('foo', 'foo',
        'bar', 'bar',
        '/', index)

So, the trick is simply print out even numbered elements:

>>> [urls[i] for i in xrange(0, len(urls), 2)]
['foo', 'bar', '/']

Now, there are some complications.

  1. If you're hosting this via wsgi, then it may be that your webserver is passing to webpy only things prefixed with (for example) /app. So the "real" URLs should be /app/foo, '/app/bar`, etc. There's no way for you to tell from your application.
  2. Your listed items could be (often are) regular expressions, so your produced list may not be a simple list of URLs. (Consider dashboard/(mail|settings|status) would permit three URLs: dashboard/mail, dashboard/settings and dashboard/status
  3. Finally, the odd-numbered item, while usually a string, may instead by of class web.application, in which you'd recurse into that application, for all of its URLs as well.

For example:

import web

def p(app, prefix=None):
    mapping = app.mapping
    for pattern, what in mapping:
        if isinstance(what, basestring):
            print "{}{}".format(prefix + '/' if prefix else '', pattern)
        else:
            p(what, prefix=pattern)


if __name__ == '__main__':
    # "blog" sub-application which handles blog-related urls                                                                                                                                  
    blog_urls = ('create', 'blog.Create', 'edit', 'blog.Edit', 'delete', 'blog.Delete')
    blog_app = web.application(blog_urls, globals())

    # "main" application which handles most urls, but passed blog URL to sub-application                                                                                                      
    main_urls = ('/account', 'account', '/settings', 'settings', '/blog', blog_app)
    main_app = web.application(main_urls, globals())
    p(main_app)

Running:

$ python foo.py
/account
/settings
/blog/create
/blog/edit
/blog/delete

Upvotes: 1

Related Questions