使用Django rest框架执行post请求

dluptydi  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(149)

我有一个Django休息框架APIView:

class MyAPIView(views.APIView):
    def post(self, request):
        field = request.POST.get("field")
        print(field)
        return Response({"field": field}, status=200)

我想使用Django API从单独的进程调用它,我是这样做的:

from django.http import HttpRequest, QueryDict

request = HttpRequest()
request.method = "POST"
request.POST = QueryDict(mutable=True)
request.POST["field"] = "5"
response = MyAPIView.as_view()(request=request)

但是当在MyAPIView中打印field时,它总是None。如何使用Django调用post方法?

qxsslcnc

qxsslcnc1#

1.如果您需要从另一个视图调用视图-请选中此answers
1.如果需要向视图发送请求
pip install requestspoetry add requests

from rest_framework.reverse import reverse
import requests as client

DOMAIN = "http://127.0.0.1:8080"

# your endpoint name (path name in urls.py)
# you can get name using django extenstions command `show_urls` if you dont know the path name
endpoint = reverse("my-api-view")

client.post(f"{DOMAIN}{endpoint}", data={"field": "5"})

django extensions
命令show_urls
用法:python manage.py show_urls
1.如果你确实需要运行某个视图的代码,为什么你不能把这个代码移到某个函数/静态方法中,然后在视图和代码的其他部分调用它呢?

相关问题