如何在Django URL模式中按请求方法调度?

编程入门 行业动态 更新时间:2024-10-27 23:18:04
本文介绍了如何在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模式中按请求方法调度?

本文发布于:2023-11-25 04:22:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628306.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   方法   如何在   URL   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!