0

我正在用 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 两次,以及它们的实现方法。

有没有办法合并/改进这个?

4

1 回答 1

2

为避免重复视图函数,请使用默认值为Nonefor的单个视图函数pk,并将其绑定到登录用户的pkif it's None请参阅url 调度程序文档中的示例

假设您的播放器是默认身份验证模型的实例user,简化版本将如下所示:

views.py
def player_info(request, pk=None):
    if pk is None:
        player = request.user
    else:
        player = get_object_or_404(user, pk=int(pk))
    # now do stuff with the player

urls.py
players_url_patterns = patterns('',
    url(r'^$',           show_list),
    url(r'^(?P<pk>\d+)/$', player_info),
    url(r'^me/$',        player_info),
)

您必须指定要绑定到视图的所有模式,但如果没有指定其他视图,则不需要两个不同的视图来默认为当前用户。

于 2013-07-22T10:33:16.823 回答