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
广告

© . All rights reserved.