首页 > 解决方案 > 如何在 GET 请求中以正确的格式显示 JSON 数据

问题描述

我在 django 和 Python 中创建了小型 API。当我执行 GET 请求时,我正在从 URL(远程 API)读取数据并存储到数据库中。一切看起来都很好,我也在我的服务器端点上显示相同的数据。但它以不可读的格式显示。

请参考以下代码view.py:

from rest_framework import generics
from customer.models import Customers
from .serializers import CustomersSerializer, CustomersKeySerializer
import json
import urllib.request
import pyodbc
from django.http import HttpResponse, JsonResponse

def customer_get(request):
    j = urllib.request.urlopen("https://web.njit.edu/~jsd38/json/customer.json")
    customer_data = json.load(j)
    cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=DAL1281;"
                      "Database=Test;"
                      "Trusted_Connection=yes;")
    cursor = cnxn.cursor()
    cursor.execute("SELECT CustomerId FROM dbo.Customers")
    CustomerIdRows = [x[0] for x in cursor.fetchall()]

    CustomerIds = Customers.objects.values_list('CustomerId', flat=True)

    for customer in customer_data:
        CustomerId = customer["@Id"]
        Name = customer["Name"]
        PhoneNumber = customer["PhoneNumber"]
        EmailAddress = customer["EmailAddress"]
        StreetLine = customer["Address"]["StreetLine1"]
        City = customer["Address"]["City"]
        StateCode = customer["Address"]["StateCode"]
        PostalCode = customer["Address"]["PostalCode"]

        if int(CustomerId) not in CustomerIds:
            cus = Customers()
            cus.CustomerId = CustomerId
            cus.Name = Name
            cus.PhoneNumber = PhoneNumber
            cus.EmailAddress = EmailAddress
            cus.StreetLine = StreetLine
            cus.City = City
            cus.StateCode = StateCode
            cus.PostalCode = PostalCode
            cus.save()

        if int(CustomerId) not in CustomerIdRows:
            cursor.execute(
            "INSERT INTO dbo.Customers(CustomerId,Name,EmailAddress,StreetLine,City,StateCode,PostalCode) VALUES (?,?,?,?,?,?,?)",
            (CustomerId,Name,EmailAddress,StreetLine,City,StateCode,PostalCode))
        cnxn.commit()
    queryset = Customers.objects.all()
    serializer_class = CustomersSerializer
    return HttpResponse(customer_data)

在此处输入图像描述

标签: pythondjango

解决方案


Django Rest Framework 提供Response而不是HttpResponse按照您的意图呈现 json 数据。

像这样使用它:

...
return Response(customer_data)

并从这里导入: from rest_framework.response import Response

一些编程技巧:

我看到了你的代码,我认为你可以让它更干净、更易读,并减少冗余部分,如下所示:

  • 用于setattr分配项目。例如setattr(cus, 'Name', nameValue)

  • 像这样获取一个json的key的值:customer.get('EmailAddress', ''),使用这个方法如果json中没有keyEmailAddress至少你可以设置一个默认值,否则会发生异常!

  • 使用 django orm 和 db 连接。我认为在 2019 年使用RAW查询并不酷 :)。顺便说一句,您的代码容易受到SQL 注入的攻击,因为您正在将未经验证的数据从外部 json API 立即传递到您的数据库查询。我不建议这样

  • 避免编写从未使用过的变量。例如serializer_class. 我还建议从您的数据库中呈现响应。例如return Response(serializer_class(many=True).to_representation(queryset)


推荐阅读