I'm writing a webapp2 application and am trying to figure out how to nest url mappings. The application is broken up into several packages, and I'd like each package to be able to specify it's own url mappings similar to the way Django does with it's include() directive. Copying from the Django documentation this would look like:
urlpatterns = [
# ... snip ...
url(r'^community/', include('django_website.aggregator.urls')),
url(r'^contact/', include('django_website.contact.urls')),
# ... snip ...
]
Would this need to be specified in app.yaml, or is there a way to specify the inclusion in webapp2.WSGIApplication([])
You can do it in webapp2.WSGIApplication. Take a look at the docs for PathPrefixRoute. PathPrefixRoute takes two arguments: the path prefix as a string, and a list of routes. The path prefix string would be 'community/' or contact/, based on your question. For the list of routes, just save a list of routes (without the path prefix) in each package you want to route to. So let's say you have a package.contact and a package.community. You could include a urls.py for each of them that looks like this:
import webapp2
from handlers import HandlerOne, HandlerTwo, etc.
ROUTE_LIST = [
webapp2.Route('/path_one', HandlerOne, 'name-for-route-one'),
webapp2.Route('/path_two', HandlerTwo, 'name-for-route-two'),
...
]
Then in your app.py, you could do this:
from package.contact import urls as contact_urls
from package.community import urls as community_urls
from webapp2_extras.routes import PathPrefixRoute
routes = [
webapp2.Route('/', RegularHandler, 'route-name'),
# ... other normal routes ...
PathPrefixRoute('/contact', contact_urls.ROUTE_LIST),
PathPrefixRoute('/community', community_urls.ROUTE_LIST),
# ... other routes ...
]
app = WSGIApplication(routes)
# now the url '/contact/path-one' will route to package.contact.handlers.HandlerOne
You could get more creative to make it more aesthetically pleasing or more Django-like, but you get the picture. Using PathPrefixRoute, all you need is a list of routes from your packages to plug them into your app routing.