2015-09-03 17 views
3

我試圖更改Pyramid hello world example,以便對金字塔服務器的任何請求都服務於同一頁面。即所有路線指向相同的視圖。這是第四走到這一步:Python Pyramid中所有地址轉到單個頁面(捕獲全部路徑)

from wsgiref.simple_server import make_server 
from pyramid.config import Configurator 
from pyramid.response import Response 

def hello_world(request): 
    return Response('Hello %(name)s!' % request.matchdict) 

if __name__ == '__main__': 
    config = Configurator() 
    config.add_route('hello', '/*') 
    config.add_view(hello_world, route_name='hello') 
    app = config.make_wsgi_app() 
    server = make_server('0.0.0.0', 8080, app) 
    server.serve_forever() 

完成所有四是改變(從Hello World示例)行:

config.add_route('hello', '/hello/{name}') 

要:

config.add_route('hello', '/*') 

所以我想路線是一個'全面'。 Iv嘗試了各種變化,無法讓它工作。有沒有人有任何想法?

感謝addvance

回答

4

catchall route(在金字塔中稱爲「遍歷子路徑」)的語法是*subpath而不是*。還有*traverse,它用於混合路由,它將路由調度和遍歷結合起來。你可以在這裏閱讀:Using *subpath in a Route Pattern

在你的視圖函數中,你將能夠通過request.subpath訪問子路徑,這是一個由catchall路徑捕獲的路徑段的元組。所以,你的應用程序應該是這樣的:

from wsgiref.simple_server import make_server 
from pyramid.config import Configurator 
from pyramid.response import Response 

def hello_world(request): 
    if request.subpath: 
     name = request.subpath[0] 
    else: 
     name = 'Incognito' 
    return Response('Hello %s!' % name) 

if __name__ == '__main__': 
    config = Configurator() 
    config.add_route('hello', '/*subpath') 
    config.add_view(hello_world, route_name='hello') 
    app = config.make_wsgi_app() 
    server = make_server('0.0.0.0', 8081, app) 
    server.serve_forever() 

不要通過自定義404處理器做到這一點,它的氣味PHP :)

+0

致謝這正是即時尋找!我幾次查看了文檔的這一部分,但我只是不習慣術語,所以沒有點擊。謝謝 – joshlk

0

您可以創建自定義錯誤處理程序(不記得了我的頭頂,但它是在金字塔文檔)和捕獲HTTP 404錯誤,並重定向/渲染你的catch-所有的路線從那裏。

鏈接我在想:http://docs.pylonsproject.org/projects/pyramid//en/latest/narr/hooks.html

我做了這樣的事情:

from pyramid.view import (
    view_config, 
    forbidden_view_config, 
    notfound_view_config 
    ) 

from pyramid.httpexceptions import (
    HTTPFound, 
    HTTPNotFound, 
    HTTPForbidden, 
    HTTPBadRequest, 
    HTTPInternalServerError 
    ) 

import transaction 
import traceback 
import logging 

log = logging.getLogger(__name__) 

#region Custom HTTP Errors and Exceptions 
@view_config(context=HTTPNotFound, renderer='HTTPNotFound.mako') 
def notfound(request): 
    if not 'favicon' in str(request.url): 
     log.error('404 not found: {0}'.format(str(request.url))) 
     request.response.status_int = 404 
    return {} 

我想你應該能夠從內有重定向到一個視圖。