我一直在挖掘金字塔,我正在寻找设置中间件来服务我的api。 我用werkzeug使用DispatchMiddleware完成了这个。
如何在金字塔中实现这一目标
project
| __init__.py
| api
| | __init__.py
| web
| | __init__.py
项目/ API /的初始化的.py
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('cornice')
api_includes(config)
config.scan() // scan only api_includes/routes
app = config.make_wsgi_app()
return app
项目/网络/的初始化的.py
def web_includes(config):
config.include('project.posts', route_prefix='/post')
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
config.add_static_view('static', 'static', cache_max_age=3600)
web_includes(config)
config.add_route('home', '/')
config.scan() // only web_includes/routes
app = config.make_wsgi_app()
return app
项目/的初始化的.py
from pyramid.config import Configurator
from api import main as api_main
from web import main as web_main
from pyramid.wsgi import wsgiapp, wsgiapp2
def main(global_configs, **settings):
web = wsgiapp2(web_main(global_configs, **settings))
api = wsgiapp2(api_main(global_configs, **settings))
config = Configurator()
config.add_view(web, name='/')
config.add_view(api, name='api')
return config.make_wsgi_app()
在评价我的api时,它可以正常工作,但是除非我指定一个不是'/'或''的名称,否则它将无法使用网络路由:
config.add_view(web, name='foo')
转到/ foo或/ foo / post works
答案 0 :(得分:3)
config.add_route('api', '/api/*subpath')
config.add_route('default', '/*subpath')
config.add_view(web, route_name='default')
config.add_view(api, route_name='api')
使用URL分派应该可以让你在应用程序的前缀中更简单地挂载东西。 URL分派中的路由按顺序匹配,因此请确保api在默认值之前运行,否则所有内容都将发送到默认路由。