跳转到主要内容

Django视图分发工具,根据请求方法分发视图

项目描述

用法

from django.conf.urls import patterns, url
from django_view_dispatch import dispatch, dispatch_strict

from . import views


urlpatterns = patterns('',
    url(r'^some_url/$', dispatch(get=views.my_view, post=views.my_view_for_post), name='events_json'),

    # you can get any keyword argument you want to specify any http verb
    url(r'^some_url/$', dispatch(get=views.my_view, put=views.create, foo=views.another_view, bar=views.baz), name='events_json'),

    # by default, if a request has an HTTP verb that hasn't been specified in
    # the dispatch() function, it will be redirected to the GET view if present
    url(r'^some_url/$', dispatch(get=views.will_get_everything_thats_not_put, put=views.stuff), name='events_json'),

    # you can change this behavior this way
    url(r'^some_url/$', dispatch(get=views.stuff, put=views.will_get_everything_thats_not_get, default="put"), name='events_json'),

    # if "default" is set to None, this behavior is disabled and and
    # HttpResponseNotAllowed will be returned
    url(r'^input/$', dispatch(post=views.my_view_for_post, default=None), name='events_json'),  # behave like @require_POST

    # a more explicit way to do that is provided with "dispatch_strict" which behave exactly like dispatch with default set to None
    url(r'^input/$', dispatch_strict(post=views.my_view_for_post), name='events_json'),
)

安装

pip install django_view_dispatch

为什么

在编程过程中,你会逐渐了解到条件判断“不好”(即“应该避免”),因为它们会增加你的代码复杂性,并可能成为错误源。

例如,在同一个视图中混合POST和GET处理可能会为错误和更复杂的代码提供良好的土壤,而将其分离则提供了一个KISS(保持简单,傻瓜也能懂)的情况,其中你有两个视图,每个视图只做一件事,而且做得很好。

Django没有提供简单或标准的方式来实现这一点,因此这个库试图解决这个问题。

我可以在URL函数中使用字符串吗?

不行,从Django 1.8开始,在模式中使用字符串来定位视图已过时,因此支持此功能没有意义。

老实说,我根本不知道如何实现这一点,也没有进行过任何研究。这也会使代码变得更加复杂。

运行测试

pip install pytest
py.test test.py

许可证

BSD。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分布

django_view_dispatch-0.1.tar.gz (2.6 kB 查看散列)

上传于 源代码

构建版本

django_view_dispatch-0.1-py2.py3-none-any.whl (4.9 kB 查看哈希值)

上传于 Python 2 Python 3

django_view_dispatch-0.1-py2.7.egg (2.8 kB 查看哈希值)

上传于 源代码

支持者