在url调度中存储布尔变量

R3t*_*rnz 3 python regex django url

以下网址定义应该传递是否results/存在于网址中:

url(r'^(?P<question_id>[0-9]+)/(?P<results>(results/)?)shorten/$', views.shorten, name='shorten')
Run Code Online (Sandbox Code Playgroud)

目前它通过results/None足够简单:

if results:
    pass
Run Code Online (Sandbox Code Playgroud)

但拥有True和更优雅False.怎么可以这样做?

Ala*_*air 6

你可以有两个URL模式并传入resultskwargs:

url(r'^(?P<question_id>[0-9]+)/results/shorten/$', views.shorten, {'results': True}, name='shorten'),
url(r'^(?P<question_id>[0-9]+)/shorten/$', views.shorten, {'results': False}, name='shorten'),
Run Code Online (Sandbox Code Playgroud)

如果您不想这样做,那么目前没有一种简单的方法可以将results字符串转换为布尔值.你可以编写一个中间件或装饰器,但这样就太过分了.