将我的 Django 视图变成 DjangoRestFramework API 端点

Making my Django Views into a DjangoRestFramework API Endpoint

我有一个支付验证视图,它使用一些参数,如密钥和其他一些身份验证参数。

我想将视图变成 API 端点,这样我就可以输入参数,然后 returns 响应。

我熟悉制作在 models.py 中具有 类 的基本端点 CRUD 端点,但这没有。

P.S:我也在使用一个有响应的外部 API,我所要做的就是发送所需的参数,然后如果它们是正确的,它returns 响应。

Views.py

def verify_paystack_payment(request):
    url = "https://api.paystack.co/transaction/verify/262762380"

    payload = {
        "email": "email@yahoo.com",
        "amount": "10000",
        "currency": "NGN",
        "reference": "262762380",
        "metadata": {
            "custom_fields": [
                {
                    "display_name": "Mobile Number",
                    "variable_name": "mobile_number",
                    "value": "+2348012345678"
                }
            ]
        }
    }

    files = {}

    headers = {
      'Authorization': 'Bearer **MY SECRET KEY**',
      'Content-Type': 'application/json'
    }

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

    return render(request, "transaction/pay.html")

如果您使用的是 Django 1.7+,那么您可以使用 JsonResponse

from django.http import JsonResponse

def verify_paystack_payment(request):
    url = "https://api.paystack.co/transaction/verify/262762380"

    payload = {
        "email": "email@yahoo.com",
        "amount": "10000",
        "currency": "NGN",
        "reference": "262762380",
        "metadata": {
            "custom_fields": [
                {
                    "display_name": "Mobile Number",
                    "variable_name": "mobile_number",
                    "value": "+2348012345678"
                }
            ]
        }
    }

    files = {}

    headers = {
      'Authorization': 'Bearer **MY SECRET KEY**',
      'Content-Type': 'application/json'
    }

    response = requests.request("GET", url, headers=headers, data= payload, files=files)
    return JsonResponse({"data":response.text})

Pre-Django 1.7 你会这样做:

import json 
from django.http import HttpResponse

def verify_paystack_payment(request):
    #Function code
    return HttpResponse(json.dumps({"data":response.text}),content_type="application/json")