多子域,通用路由模式

时间:2013-10-02 20:34:40

标签: python design-patterns subdomain pyramid routes

所以我想要的是一个金字塔应用程序,其中包含以下内容:

  • 如果用户转到control.blah.com/,我希望他们获得第A页
  • 如果用户转到www.blah.com/,我希望他们获取第B页

我尝试了什么:

# Pregen for "Control" Subdomain
def pregen(request, elements, kw):
    kw['_app_url'] = 'http://control.blah.com'
    return elements, kw

# Custom predicate for "Control" Subdomain
def req_sub(info, request):
    return request.host.startswith('control')

def main(global_config, **settings):
    """
    This function returns a Pyramid WSGI application.
    """

    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)

    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.add_jinja2_extension('jinja2.ext.do')
    config.include('pyramid_tm')
    config.add_static_view('static', 'static', cache_max_age=3600)

    # Control Subdomain
    config.add_route('control_index', '/', custom_predicates=(req_sub, ),
            pregenerator=pregen)

    # Main Subdomain
    config.add_route('index', '/')

    config.scan()

    app = config.make_wsgi_app()

    return app

现在,转到control.blah.com/会导致调用control_index视图,但当我转到www.blah.com/时,我会收到404 Not Found。

同样,如果我在子域行之前移动config.add_route('index', '/'),那么我会遇到相反的问题。

是否有可能得到我想要的,或者路线需要有不同的模式(AKA。不能有/模式的2条路线

1 个答案:

答案 0 :(得分:0)

您对自定义谓词的使用看起来是正确的,但对于与相同模式发生冲突的路线,您可能是正确的。这就是我想要的:

class DomainOverrideMiddleware(object):

    def __init__(self, app):
        self.application = app

    def __call__(self, environ, start_response):
        if "HTTP_HOST" in environ and "control.blah.com" in environ['HTTP_HOST']:
            environ['PATH_INFO'] = "/control" + environ['PATH_INFO']
        return self.application(environ, start_response)



def main(global_config, **settings):
    """
    This function returns a Pyramid WSGI application.
    """

    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)

    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.add_jinja2_extension('jinja2.ext.do')
    config.include('pyramid_tm')
    config.add_static_view('static', 'static', cache_max_age=3600)

    # Control Subdomain
    #Change this subdomain to handle the modified path
    config.add_route('control_index', '/control/', custom_predicates=(req_sub, ),
            pregenerator=pregen)

    # Main Subdomain
    config.add_route('index', '/')

    config.scan()

    #Change this to call the override
    app = DomainOverrideMiddleware(config.make_wsgi_app())

因此,这会在应用程序内部修改路径,使用'/ control'前缀来处理不同的路由(避免冲突),但是用户的路径应该保持不变。 未经测试,但在理论上有效。