在Python路由中预处理路由参数

时间:2022-12-13 11:02:56

I'm using Routes for doing all the URL mapping job. Here's a typical route in my application:

我正在使用Routes来完成所有的URL映射工作。这是我的应用程序中的典型路线:

map.routes('route', '/show/{title:[^/]+}', controller='generator', filter_=postprocess_title)

Quite often I have to strip some characters (like whitespace and underscore) from the {title} parameter. Currently there's one call per method in the controller to a function that does this conversion. It's not terribly convenient and I'd like Routes to do this job. Is it possible?

我经常要从{title}参数中删除一些字符(如空格和下划线)。目前,控制器中的每个方法都有一个调用来执行此转换的函数。这不是非常方便,我希望Routes能够完成这项工作。可能吗?

1 个解决方案

#1


I am not familiar with Routes, and therefore I do not know if what you're after is possible with Routes.

我对Routes不熟悉,因此我不知道你使用Routes可以获得什么。

But perhaps you could decorate your controller methods with a decorator that strips characters from parameters as needed?

但也许您可以使用装饰器来装饰控制器方法,装饰器根据需要从参数中去除字符?

Not sure if this would be more convenient. But to me, using a decorator has a different 'feel' than doing the same thing inline inside the controller method.

不确定这是否更方便。但对我来说,使用装饰器与在控制器方法内部执行相同操作具有不同的“感觉”。

For instance:


@remove_spaces_from('title')
def my_controller(...):
    ...

If you are not familiar with decorators, a google search for "python decorators" will get you started. A key point to remember: When arguments are needed for a decorator, you need two levels of wrapping in the decorator.

如果您不熟悉装饰器,Google搜索“python decorators”将帮助您入门。要记住的关键点:当装饰器需要参数时,装饰器需要两级包装。

#1


I am not familiar with Routes, and therefore I do not know if what you're after is possible with Routes.

我对Routes不熟悉,因此我不知道你使用Routes可以获得什么。

But perhaps you could decorate your controller methods with a decorator that strips characters from parameters as needed?

但也许您可以使用装饰器来装饰控制器方法,装饰器根据需要从参数中去除字符?

Not sure if this would be more convenient. But to me, using a decorator has a different 'feel' than doing the same thing inline inside the controller method.

不确定这是否更方便。但对我来说,使用装饰器与在控制器方法内部执行相同操作具有不同的“感觉”。

For instance:


@remove_spaces_from('title')
def my_controller(...):
    ...

If you are not familiar with decorators, a google search for "python decorators" will get you started. A key point to remember: When arguments are needed for a decorator, you need two levels of wrapping in the decorator.

如果您不熟悉装饰器,Google搜索“python decorators”将帮助您入门。要记住的关键点:当装饰器需要参数时,装饰器需要两级包装。