Django 如何在webapp2.WSGIApplication中嵌套url映射
我正在编写一个webapp2应用程序,并试图找出如何嵌套url映射。应用程序分为几个包,我希望每个包都能够指定自己的url映射,类似于Django使用include()指令的方式。从Django文档中复制以下内容:Django 如何在webapp2.WSGIApplication中嵌套url映射,django,webapp2,Django,Webapp2,我正在编写一个webapp2应用程序,并试图找出如何嵌套url映射。应用程序分为几个包,我希望每个包都能够指定自己的url映射,类似于Django使用include()指令的方式。从Django文档中复制以下内容: urlpatterns = [ # ... snip ... url(r'^community/', include('django_website.aggregator.urls')), url(r'^contact/', include('django_w
urlpatterns = [
# ... snip ...
url(r'^community/', include('django_website.aggregator.urls')),
url(r'^contact/', include('django_website.contact.urls')),
# ... snip ...
]
这是否需要在app.yaml中指定,或者是否有办法在webapp2.WSGIApplication([])中指定包含内容您可以在
webapp2.WSGIApplication
中指定。请看下面的图片。PathPrefixRoute接受两个参数:作为字符串的路径前缀和路由列表。根据您的问题,路径前缀字符串应为'community/'
或contact/
。对于路由列表,只需在要路由到的每个包中保存路由列表(不带路径前缀)。假设您有一个软件包。联系人
和一个软件包。社区
。您可以为每个URL包含一个URL.py,如下所示:
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'),
...
]
然后在app.py中,您可以执行以下操作:
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
你可以更具创造性,使它更美观或更像Django,但你明白了。使用PathPrefixRoute,您只需从软件包中获得一个路由列表,即可将其插入应用程序路由。谢谢。那看起来像我要找的。