我想要一种以集中方式自动将 GET 和 POST 请求路由到后续方法的方法。 我想通过以下方式创建我的处理程序。
class MyHandler(BaseHandler):
def get(self):
#handle get requests
def post(self):
#handle post requests
这是webapp2做的,我非常喜欢这种风格,可以在Django中做吗? 我还想要类方法样式的 View 。应该写什么样的BaseHandler和router。
提示:使用 Django 通用 View 。
最佳答案
这在 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'),
)
关于python - Django GET 和 POST 处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16668441/