Python Pyramid - 路由字首



很多時候,類似的 URL 模式在多個 Python 程式碼模組中使用不同的路由進行註冊。例如,我們有一個 student_routes.py 檔案,其中 /list 和 /add URL 模式分別與 'list' 和 'add' 路由註冊。與這些路由關聯的檢視函式分別是 list()add()

#student_routes.py
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

@view_config( route_name='add')
def add(request):
   return Response('add student')
@view_config(route_name='list')
def list(request):
   return Response('Student list')
   
def students(config):
   config.add_route('list', '/list')
   config.add_route('add', '/add')
   config.scan()

這些路由最終會在呼叫 students() 函式時註冊。

同時,還有一個 book_routes.py 檔案,其中相同的 URL /listadd/ 分別註冊到 'show' 和 'new' 路由。它們關聯的檢視分別是 list() 和 add()。該模組具有 books() 函式,用於新增路由。

#book_routes.py
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

@view_config( route_name='new')
def add(request):
   return Response('add book')
@view_config(route_name='show')
def list(request):
   return Response('Book list')
def books(config):
   config.add_route('show', '/list')
   config.add_route('new', '/add')
   config.scan()

顯然,URL 模式之間存在衝突,因為 '/list' 和 '/add' 各指向兩個路由,並且必須解決此衝突。這可以透過使用 config.include() 方法的 route_prefix 引數來完成。

config.include() 的第一個引數是新增路由的函式,第二個引數是 route_prefix 字串,它將被新增到包含函式中使用的 URL 模式之前。

因此,語句

config.include(students, route_prefix='/student')

將導致 '/list' URL 模式更改為 '/student/list',而 '/add' 則變為 'student/add'。類似地,我們可以在 books() 函式中為這些 URL 模式新增字首。

config.include(books, route_prefix='/books')

示例

啟動伺服器的程式碼如下所示:

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from student_routes import students
from book_routes import books

if __name__ == '__main__':
   with Configurator() as config:
      config.include(students, route_prefix='/student')
      config.include(books, route_prefix='/book')
      app = config.make_wsgi_app()
   server = make_server('0.0.0.0', 6543, app)
   server.serve_forever()

輸出

讓我們執行以上程式碼,並透過以下 CURL 命令測試路由。

C:\Users\Acer>curl localhost:6543/student/list
Student list
C:\Users\Acer>curl localhost:6543/student/add
add student
C:\Users\Acer>curl localhost:6543/book/add
add book
C:\Users\Acer>curl localhost:6543/book/list
Book list
廣告