pythonturbogears2turbogears

Which characters does TurboGears replace in the URL?


I have a simple TurboGears 2 script, named app.py:

#!/usr/bin/env python3

from wsgiref.simple_server import make_server
from tg import expose, TGController, AppConfig

class RootController(TGController):
    @expose()
    def all__things(self):
        return "Hello world!"

config = AppConfig(minimal=True, root_controller=RootController())

print("Serving on port 5000...")
httpd = make_server('', 5000, config.make_wsgi_app())
httpd.serve_forever()

When I run app.py and visit http://localhost:5000/all__things, I see "Hello world!" as expected. But these URLs also work:

http://localhost:5000/all--things
http://localhost:5000/all@@things
http://localhost:5000/all$$things
http://localhost:5000/all++things
http://localhost:5000/all..things
http://localhost:5000/all,,things

As well as combinations:

http://localhost:5000/all-_things
http://localhost:5000/all_-things
http://localhost:5000/all-@things
http://localhost:5000/all@-things
http://localhost:5000/all$@things
http://localhost:5000/all@$things

Et cetera...

What is the complete list of characters that can be substituted for an underscore in TurboGears URLs?

Also, can this feature be restricted to only substitute certain characters? Ideally, I want URLs with dashes (http://localhost:5000/all--things) to work, and URLs with underscores (http://localhost:5000/all__things) or any other strange characters to not work.


Solution

  • That's managed by the path_translator which can be configured through the dispatch_path_translator option in app_cfg.py. It can be disabled by passing None or providing a custom function.

    Any function provided will receive the part of the path currently being processed and must return it normalised.

    The default path translator is based on string.punctuation (see https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Lib/string.py#L31 )

    In case you have custom routing needs I suggest you consider https://github.com/TurboGears/tgext.routes which might help you in more complex cases through the @route decorator.