本文介绍了从 DjangoRestFramework 中的 API 端点动态请求数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从外部来源进行一些 API 调用,但希望使其动态化,而不是在提供的 DRF UI 中手动将参考编号放入我的视图中.

I am making some API calls from an external source but would like to make it dynamic instead of manually putting the reference number in my views in the DRF UI provided.

我想要的是,在我的 DRF UI 中,我应该有一个字段,当我输入参考号时,我应该从 API 获得响应,我手动成功地做到了这一点,但我想让它从DRF 用户界面.

What I want is that in my DRF UI, I should have a field whereby when I enter a reference number, I should get the response from from the API, I am successfully doing this manually but I want to make it dynamic from the DRF UI.

我还想在我的 DRF UI 中获得格式更好的 JSON 响应.下面的图片可以更好地解释我的意思

I would also like to get a better formatted JSON Response in my DRF UI. An image is below to better explain what I meant

视图.py

class Paystack(APIView):
    def get(self, request):
        url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}"
        payload = {}
        files = {}
        headers = {
            'Authorization': 'Bearer SECRET_KEY',
            'Content-Type': 'application/json'
        }

        response = requests.request("GET", url, headers=headers, data= payload, files=files)
        return Response(response)

    def post(self, request):
        url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}"
        payload = {}
        files = {}
        headers = {
            'Authorization': 'Bearer SECRET_KEY',
            'Content-Type': 'application/json'
        }

        response = requests.request("GET", url, headers=headers, data= payload, files=files)
        return Response(response)

urls.py

from django.urls import path, include
from .views import *
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('paystack', Paystack, basename='paystack')

urlpatterns = [
    path('paystack/', Paystack.as_view(), name='paystack'),
]

目前,我的 DRF UI 看起来像这样,

Presently, my DRF UI looks likes this,

推荐答案

如果您希望能够在 DRF UI 中获取 reference_id,您必须定义一个序列化程序并从中捕获值,或者,您可以定义一个要求提供参考 ID 的网址格式.

If you want to be able to get reference_id in your DRF UI, you must either define a serializer and catch the value from that, or, you can define a URL pattern which asks for a reference ID.

你可以这样做

在 urls.py

urlpatterns = [
path('paystack/<str:reference_id>', Paystack.as_view(), name='paystack'),

]

在您的 views.py

class Paystack(APIView):

    def get(self, request, reference_id):
        url = f"https://api.paystack.co/transaction/verify/{reference_id}"
        payload = {}
        files = {}
        headers = {
            'Authorization': 'Bearer SECRET_KEY',
            'Content-Type': 'application/json'
        }

        response = requests.request("GET", url, headers=headers, data= payload, files=files)
        return Response(response)

这篇关于从 DjangoRestFramework 中的 API 端点动态请求数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 15:25