如何将请求URL还原为配置中定义的路由模式?
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

