如何在Django URL模式中按请求方法调度? [英] How can you dispatch on request method in Django URLpatterns?

查看:64
本文介绍了如何在Django URL模式中按请求方法调度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显如何创建从URL正则表达式分派的URLPattern:

It's clear how to create a URLPattern which dispatches from a URL regex:

(r'^books/$', books),

其中图书可以根据请求的方法进一步派发:

where books can further dispatch on request method:

def books(request):
    if request.method == 'POST':
        ...
    else:
        ...

我想知道是否有一种将请求方法包含在URLPattern中的惯用方式,将所有调度/路由信息都保留在一个位置,例如:

I'd like to know if there is an idiomatic way to include the request method inside the URLPattern, keeping all dispatch/route information in a single location, such as:

(r'^books/$', GET, retrieve-book),
(r'^books/$', POST, update-books),
(r'^books/$', PUT, create-books),


推荐答案

一种单一的查看方法是您通常将某种页面内容呈现为要提交的表单的上下文。

The reason it's done as a single view method is that you're usually rendering some kind of page content as context for the form you're about to submit.

无论如何,我的回复理由这:从您的示例URLConf那里看起来好像您正在使用Django构建REST Web服务-如果是这种情况,那么使用相当不错的 django-piston 自动创建您的资源/集合。它使用基于类的处理程序,该处理程序根据请求中的HTTP方法自动重定向到适当的方法(在您的情况下为get-books,update-books,create-books)

Anyway, my reason for replying it this: from your sample URLConf there it looks like you're building a REST webservice with Django -- if this is the case, you might really benefit from using the rather good django-piston to automatically create your resources/collections. It uses class-based handlers that automatically redirect to the appropriate method (get-books, update-books, create-books in your case) based on the HTTP method in the request

UPDATE(四年后!),而django-piston仍然存在(并且可以工作)时, Django REST Framework 是当今更为复杂,有据可查和扩展的选择。

UPDATE (four years later!) while django-piston still exists (and works), Django REST Framework is a much more sophisticated, documented and extended choice these days.

这篇关于如何在Django URL模式中按请求方法调度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆