Django GET和POST处理方法 [英] Django GET and POST handling methods

查看:331
本文介绍了Django GET和POST处理方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一种将GET和POST请求自动路由到后续方法的集中式方法。
我想通过以下方式创建处理程序。

I want a way to automatically route GET and POST requests to subsequent methods in a centralized way. I want to create my handler in the following way.

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

    def post(self):
        #handle post requests

这是webapp2的功能,我非常喜欢样式,可以在Django中完成吗?
我也希望使用类方法样式的视图。我应该写什么样的BaseHandler和路由器。

This is what webapp2 does and I very much like the style, is it possible to do in Django? I also want the view in Class-method style. What kind of BaseHandler and router should I write.

提示:请使用django通用视图。

HINT: Use django generic views.

推荐答案

在Django中,基于类的视图。您可以扩展通用类 View 并添加诸如 get() post()之类的方法 put()等。例如-

This is supported in Django as class based views. You can extend the generic class View and add methods like get(), post(), put() etc. E.g. -

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()方法处理此问题-

The dispatch() method from View class handles this-


调度(请求,* args,** kwargs)



视图视图的一部分–
方法接受请求参数和参数,并返回
HTTP响应。

dispatch(request, *args, **kwargs)

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

默认实现将检查HTTP方法并尝试
委托给与HTTP方法匹配的方法;

默认情况下,HEAD请求是将GET委托给get()的
,委托给post()的POST等。将被委托给get()。如果您需要
以不同于GET的方式处理HEAD请求,则可以覆盖
head()方法。

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.

默认实现还会将request,args和kwargs设置为
实例变量,因此视图上的任何方法都可以知道调用视图的请求的完整
详细信息。

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.

然后您可以在<$ c中使用它$ c> 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'),
)

这篇关于Django GET和POST处理方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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