python - 如何在 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)
解决方案
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)
推荐阅读
- r - 在 R 中选择每个日期每个 ID 的第一个正匹配
- android - 使用 Glide 检索时图像变得模糊
- python - 错误预期类型 StringIO,改为 str
- c# - 当 IsSelected 时 WPF DataGrid 设置文本换行
- cordova - 无法解析配置“:app:debugCompileClasspath”的所有文件
- html - 旋转图像不平滑动画
- jquery - 自动注销 jQuery 在 Chrome 中工作但在 Firefox 中不工作
- sql - SQL 查询 - 在多 ID 查询中每个 ID 仅选择 500 个条目?
- android - 如果应用程序失去焦点,强制 android 应用程序完全重新启动
- php - Redux 框架 - 自定义字体过滤器