简体   繁体   中英

Django GET and POST handling methods

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

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.

HINT: Use django generic views.

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

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')

The dispatch() method from View class handles this-

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.

Then you can use it in 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'),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM