Я создал небольшой API в django и Python. Я читаю данные из URL (удаленный API) и сохраняю их в базу данных при выполнении запроса GET. Все выглядит хорошо, и я показываю те же данные на конечной точке моего сервера. Но они отображаются в нечитаемом формате.
Пожалуйста, обратитесь к приведенному ниже коду 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)
