我用Django和Python创建了小型API。当我执行GET请求时,我正在从URL(Remote 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)
答案 0 :(得分:0)
Django Rest Framework提供了Response
而不是HttpResponse
来呈现您想要的json数据。
像这样使用它:
...
return Response(customer_data)
并从此处导入:from rest_framework.response import Response
我看到了您的代码,我认为您可以使其更简洁,更具可读性,并减少以下多余的部分:
使用setattr
分配项目。例如setattr(cus, 'Name', nameValue)
获取json的键值,例如:customer.get('EmailAddress', '')
,使用此方法,如果EmailAddress
的json中没有键,则至少可以设置默认值,否则可以设置例外会发生!
使用Django orm和db连接。我认为在2019年使用 RAW 查询并不酷:)。顺便说一句,您的代码容易受到 SQL注入的攻击,因为您会将未经验证的数据立即从外部json API传递到数据库查询。我不建议在 ALL 。
避免编写从未使用过的变量。例如serializer_class
。我也建议从您的数据库呈现响应。例如return Response(serializer_class(many=True).to_representation(queryset)