簡體   English   中英

使用 Django rest 框架執行發布請求

[英]Perform post request using Django rest framework

我有一個 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 方法?

  1. 如果您需要從另一個視圖調用視圖 - 檢查這個答案

  2. 如果您需要向視圖發送請求

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 擴展

命令 show_urls

用法: python manage.py show_urls

  1. 如果您需要准確地運行某個視圖的代碼,為什么不能將此代碼移動到某個函數/靜態方法並在視圖和代碼的其他部分中調用它?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM