You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将请求URL还原为配置中定义的路由模式?

Best Way to Retrieve the Original Route Pattern in Pyramid

Forget regex—Pyramid gives you a straightforward, built-in way to get the exact route pattern you defined when a request matches it. Here's how to do it:

Step 1: Access the Matched Route from the Request

When a request hits your endpoint, Pyramid attaches the matched route object to the request object as request.matched_route. This object contains all the metadata about the route, including the original pattern you configured.

Step 2: Use the pattern Attribute

The matched_route object has a pattern property that directly returns the route string you set up (like 'book/{id}').

Example View Function

Here's a complete working example of a view that returns the route pattern when you hit the endpoint:

from pyramid.view import view_config

@view_config(route_name='book', renderer='string')
def book_view(request):
    # Fetch the original route pattern directly from the matched route
    route_pattern = request.matched_route.pattern
    return route_pattern

How It Works

When you send a GET request to localhost:8000/book/2, this view will respond with the exact string book/{id}—no regex parsing required.

Why This Is Better Than Regex

  • Zero maintenance: You don’t have to update a regex every time you modify your route pattern—Pyramid keeps track of it for you.
  • Built-in reliability: You’re using Pyramid’s internal route tracking instead of writing custom, error-prone regex.
  • Clean, concise code: It’s a single line of code that does exactly what you need.

If you need to access this pattern elsewhere in your app (like middleware or another view), you can still use request.matched_route.pattern as long as the request has successfully matched a route.

内容的提问来源于stack exchange,提问作者AverageJoe9000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:20:57