我正在用 django 实现一个 Web 服务(没有 html,没有模板,只有 JSON),我希望能够合并一些 url 模式代码,这样它就不会重复。
这是需要支持的网址:
host/players/12/ this returns the player's 12 info
host/players/me/ this returns the logged player info
如果登录的玩家的 id 为 12,则两者返回相同。我还需要支持更多的 url,例如:
host/players/12/other-stuff/
host/players/me/other-stuff/
我怎样才能避免对 /other-stuff/ 使用两种不同的视图方法?
这是我到目前为止所拥有的:
instance_url_patterns = patterns('',
url(r'^$', instance_with_id),
url(r'^other_stuff$', other_stuff_with_id),
# more suff goes in here
)
current_instance_url_patterns = patterns('',
url(r'^$', instance_without_id),
url(r'^other_stuff$', other_stuff_without_id),
# more suff goes in here
)
players_url_patterns = patterns('',
url(r'^$', show_list),
url(r'^(?P<pk>\d+)', include(instance_url_patterns)),
url(r'^me/$', include(current_instance_url_patterns)),
)
# This is the origin of all the above urls (located in urls.py)
urlpatterns = patterns('',
url(r'^players/', include(players.relation_url_patterns)),
)
请注意我如何需要在 instance_url_patterns 和 current_instance_url_patterns 中拥有所有 url 两次,以及它们的实现方法。
有没有办法合并/改进这个?