简体   繁体   English

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

[英]Django class based views get post data and send response

Working on an Api I wanted to give class based views in Django a go. 在Api上工作时,我想随意使用Django中基于类的视图。

This is what I got so far: 这是我到目前为止所得到的:

urls.py urls.py

from django.conf.urls import url

from .api import Api

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

api.py api.py

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

When calling this code from Postman I keep getting 2 issues: 从邮递员调用此代码时,我不断遇到2个问题:

Post data 发布数据

In postman I have set a value in the Post headers but when I use the debugger to check the POST data it just isn't there. 在邮递员中,我在Post标头中设置了一个值,但是当我使用调试器检查POST数据时,它就不存在了。

Return HttpResponse 返回HttpResponse

I keep getting the error The view api.api.Api didn't return an HttpResponse object. It returned None instead. 我不断收到错误The view api.api.Api didn't return an HttpResponse object. It returned None instead. The view api.api.Api didn't return an HttpResponse object. It returned None instead.

When I change the post method to a get method and send a get request with Postman I get the same result. 当我将post方法更改为get方法并与Postman发送get请求时,我得到的结果相同。

You need to do: 您需要做:

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

You're not returning anything, and a function returns None by default. 您什么都不返回,默认情况下一个函数返回None

Also, you probably want your url as r'^$' 另外,您可能希望将网址设为r'^$'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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