我试图为我的django应用程序创建视图,以便利用我之前创建的模型。模型是世界各大洲/国家,视图旨在返回它们的字符串数据,具体取决于所谓的。
调用视图以返回JSON / JSONP格式化数据,以及与单个国家/地区相关的数据或与大陆相关的数据。
我首先尝试为单个国家/地区创建视图,但我并不完全确定我所做的事情是否完全正确。
def country_json(request,continent_code,country_code):
country = Country(code = country_code)
country.save()
obj = json.dumps(country.__dict__)
return HttpResponse(obj, content_type="application/json")
我必须找出一种方法来检查我是否必须返回JSON / JSONP,但我认为通过查看请求(检查请求是否有回调?)应该会有点简单,但是我是不完全确定我现在所拥有的东西现在是否适用于我想在这个阶段实现的目标。
国家/地区的模型类似于
class Country(models.Model):
name = models.CharField(max_length=60, default='', unique=True)
code = models.CharField(max_length=3, default='', unique=True)
continent = models.ForeignKey(Continent, default='', related_name='countries')
def __init__(self):
self.area = models.PositiveIntegerField(default=0)
self.population = models.PositiveIntegerField(default=0)
self.capital = models.CharField(max_length=60, default='')
def __str__(self):
return '%s %s %s %s %s %s' % (self.name, self.code, self.capital, self.population, self.area, self.continent)
class Meta:
ordering = ["name"]
verbose_name_plural = "countries"
和视图应该返回的json / jsonp看起来像这样(例子)
JSON:
{
"area": 337030,
"population": 5244000,
"capital": "Helsinki"
}
JSONP:
myCallbackFunction({
"area": 337030,
"population": 5244000,
"capital": "Helsinki"
})
是否有任何既定的方法来测试我的视图如何工作,看看它尝试返回哪种数据?
这是我尝试实现的良好开端,还是有一些错误/错误的做法?
编辑:
这个视图似乎或多或少地适用于单个国家的JSON,但是现在我必须添加另一个分支,以便在需要时将其转换为JSONP
def country_json(request, continent_code, country_code):
all_countries = Country.objects.all()
for country in all_countries:
if country.code == country_code:
area = country.area
population = country.population
capital = country.capital
dictionary = dict([('area', area), ('population', population), ('capital', capital)])
obj = json.dumps(dictionary, indent=4)
return HttpResponse(obj, content_type="application/json")
答案 0 :(得分:0)
这适用于JSON和JSONP,但我没有很好的方法来测试它,除了专门为此构建的测试功能。
from django.http import Http404
from django.http import HttpResponse
from django.http import JsonResponse
import json
from .models import Continent, Country
def continent_json(request, continent_code):
all_continents = Continent.objects.all()
my_dictionary = {}
for continent in all_continents:
if continent.code == continent_code:
for country in continent.countries.all():
my_dictionary[country.code] = country.name
response = JsonResponse(my_dictionary)
response.status_code = 200
callback = request.GET.get('callback')
if not callback:
return HttpResponse(response, content_type="application/json")
response = '{0}({1})'.format(callback, response)
return HttpResponse(response, content_type="application/javascript")
raise Http404("Not implemented")
def country_json(request, continent_code, country_code):
all_countries = Country.objects.all()
for country in all_countries:
if country.code == country_code:
if country.continent.code == continent_code:
area = country.area
population = country.population
capital = country.capital
dictionary = dict([('area', area), ('population', population), ('capital', capital)])
obj = json.dumps(dictionary, indent=4)
response = JsonResponse(dictionary)
response.status_code = 200
callback = request.GET.get('callback')
if not callback:
return HttpResponse(response, content_type="application/json")
response = '{0}({1})'.format(callback, response)
return HttpResponse(response, content_type="application/javascript")
raise Http404()