如何在django urlpatterns中基于HTTP方法进行区分 [英] how to discriminate based on HTTP method in django urlpatterns

查看:202
本文介绍了如何在django urlpatterns中基于HTTP方法进行区分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找到有关这方面的信息时遇到困难,可能这不是正确的方法。我想根据http方法(GET或POST或DELETE或PUT)将请求路由到两个不同的视图函数。

I'm having some difficulties finding information about this, probably it's not the right approach. I'd like to route a request to two different view functions based on the http method (GET or POST or DELETE or PUT).

通常在REST中完成apis,这意味着相同的URL根据HTTP方法有不同的含义。

As it is usually done in REST apis, this would mean that the same url has different meaning based on the HTTP method.

我没有看到在urls.py文件中执行此操作的方法django,我想要的是:

I don't see a way to do this in the urls.py file of django, I'd like something like:

url(r'^tasks$', 'app.views.get_tasks', method='get'),
url(r'^tasks$', 'app.views.create_task',  method='post'),

(注意:我正在使用django 1.4)

(note: I'm working with django 1.4)

推荐答案

我不认为你可以使用不同的功能来完成这个功能,而不必为URL添加一堆逻辑(这从来不是一个好主意),但是你可以检查函数内的请求方法:

I don't think you can do this with different functions without adding a bunch of logic to the URL (which is never a good idea), but you can check inside the function for the request method:

def myview(request):
    if request.method == 'GET':
        # Code for GET requests
    elif request.method == 'POST':
        # Code for POST requests

您还可以切换到<一个href =https://docs.djangoproject.com/en/1.9/ref/class-based-views/ =nofollow>基于类的视图。然后,您只需要为每个HTTP方法定义一个方法:

You could also switch to class-based views. You would then only need to define a method for each of the HTTP methods:

class CreateMyModelView(CreateView):
    def get(self, request, *args, **kwargs):
        # Code for GET requests

    def post(self, request, *args, **kwargs):
        # Code for POST requests

如果你决定去基于类的路由,另一个好的资源是 http://ccbv.co.uk/

If you decide to go the class-based route, another good resource is http://ccbv.co.uk/.

这篇关于如何在django urlpatterns中基于HTTP方法进行区分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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