python - Django GET 和 POST 处理方法

标签 python django

我想要一种以集中方式自动将 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/

相关文章:

python - 函数返回列表中有多少整数元素是同一列表中其他元素的精确平方

python - 如何使用python从mysql表数据写入excel

python - 遍历 numpy 数组列的所有成对组合

django - 使用 Django 启动和停止定期后台任务

python - Celery 任务相同的时间表但有偏移

python - 如何在 django 中自定义下拉列表表单元素?

python - 在 CreateView 上制作表单字段的正确 Django 方法,但在 UpdateView 上是可选的?

python - 这个算法优化了吗?不然还能怎么用呢?

python - Bokeh :选择要在图中显示的 x 轴(不是数字)

django - 无法从公共(public) IP 访问我的 AWS Lightsail Django 应用程序