Django GET和POST处理方法

2024-05-16 09:45:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望有一种方法能够自动地将GET和POST请求以集中式的方式路由到后续方法。 我想用以下方式创建我的处理程序。

class MyHandler(BaseHandler):
    def get(self):
        #handle get requests

    def post(self):
        #handle post requests

这就是webapp2所做的,我非常喜欢它的风格,在Django中可以做到吗? 我还想要类方法样式的视图。我应该写什么样的BaseHandler和router。

提示:使用django泛型视图。


Tags: 方法self视图处理程序路由getdef方式
1条回答
网友
1楼 · 发布于 2024-05-16 09:45:46

在Django中,它作为class based views支持。您可以扩展泛型类View,并添加诸如get()post()put()等方法,例如-

from django.http import HttpResponse
from django.views.generic import View

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('This is GET request')

    def post(self, request, *args, **kwargs):
        return HttpResponse('This is POST request')

来自View类的dispatch()方法处理这个-

dispatch(request, *args, **kwargs)

The view part of the view – the method that accepts a request argument plus arguments, and returns a HTTP response.

The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.

By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.

The default implementation also sets request, args and kwargs as instance variables, so any method on the view can know the full details of the request that was made to invoke the view.

然后你可以在urls.py中使用它-

from django.conf.urls import patterns, url

from myapp.views import MyView

urlpatterns = patterns('',
    url(r'^mine/$', MyView.as_view(), name='my-view'),
)

相关问题 更多 >