基于Django类的视图获取发布数据并发送响应

时间:2016-05-08 17:51:47

标签: python django django-class-based-views

在Api上工作我想在Django中给出基于类的视图。

这是我到目前为止所得到的:

urls.py

scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do

api.py

from django.conf.urls import url

from .api import Api

urlpatterns = [
    url(r'^', Api.as_view())
]

从Postman调用此代码时,我不断遇到2个问题:

发布数据

在邮递员中,我在Post标头中设置了一个值,但是当我使用调试器检查POST数据时,它就不存在了。

返回HttpResponse

我一直收到错误from django.http import HttpResponse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View class Api(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): super(Api, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): return HttpResponse("result") def get(self, request): return HttpResponse("result")

当我将post方法更改为get方法并使用Postman发送get请求时,我得到相同的结果。

1 个答案:

答案 0 :(得分:5)

你需要这样做:

return super(Api, self).dispatch(request, *args, **kwargs)

您没有返回任何内容,默认情况下函数会返回None

此外,您可能希望自己的网址为r'^$'

相关问题