我在Django中编写了一个应用程序,它使用URL中的[year]/[month]/[title-text]
来标识新闻项目。要管理这些项目,我已经定义了许多网址,每个网址都以上面的前缀开头。如何在Django中编写请求过滤器/预处理器
urlpatterns = patterns('msite.views',
(r'^(?P<year>[\d]{4})/(?P<month>[\d]{1,2})/(?P<slug>[\w]+)/edit/$', 'edit'),
(r'^(?P<year>[\d]{4})/(?P<month>[\d]{1,2})/(?P<slug>[\w]+)/$', 'show'),
(r'^(?P<year>[\d]{4})/(?P<month>[\d]{1,2})/(?P<slug>[\w]+)/save$', 'save'),
)
我在想,如果有在Django的机制,这让我预处理给定的请求的意见edit
,show
和save
。它可以解析参数,例如year=2010, month=11, slug='this-is-a-title'
并从中提取模型对象。
的好处是,我能确定我的看法
def show(news_item):
'''does some stuff with the news item, doesn't have to care
about how to extract the item from request data'''
...
,而不是
def show(year, month, slug):
'''extract the model instance manually inside this method'''
...
什么是解决这个的Django的方法是什么? 或者更通用的方式,有没有一些机制来实现请求过滤器/预处理器,例如在JavaEE和Ruby on Rails中?
我还有很多阅读,直到我得到这个完全。在Django中,过滤器似乎不是那么简单。 – nre 2010-09-13 13:20:40
如在Model.objects.filter()中一样过滤对象? – 2010-09-13 13:31:13
很确定他在谈论一个方法,它在发送到实际的请求处理程序之前过滤(预处理)请求。 Java/Spring中的同义词将是一个拦截器......在Rails中它将是before_filter。 – threejeez 2013-06-04 14:56:28