嗨。
对于Django中我无法解决的错误提供了帮助
我无法输入以读取json。
应用程序通过以下形式输入数据:纬度,经度和服务。
然后查询外部api并返回json
您发送给我的错误是:
Internal Server Error: /search/
Traceback (most recent call last):
File "/home/sebasaade/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/sebasaade/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/sebasaade/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sebasaade/env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/sebasaade/env/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/home/sebasaade/env/src/weather_site/main/views.py", line 98, in get
data['ACCUWEATHER'] = self.get_data_accuweather(**required_data)
File "/home/sebasaade/env/src/weather_site/main/views.py", line 43, in get_data_accuweather
data_response = consumer.consumer_api(service, location_endpoint)
File "/home/sebasaade/env/src/weather_site/main/consumer.py", line 20, in consumer_api
return request_url(url_get_endpoint)
File "/home/sebasaade/env/src/weather_site/main/consumer.py", line 8, in request_url
data = response.json()
File "/home/sebasaade/env/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[04/May/2020 13:06:13] "GET /search/?csrfmiddlewaretoken=oTixzqGqkaAJgIV10gN8MFVsfkpbFeXYptmDnIUzVA5qnqxOnBMTmatXzWIkSM1w&latitude=44&longitude=33&service=accuweather HTTP/1.1" 500 115535
我分享代码
views.py
from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import JsonResponse
from django.http import HttpResponseRedirect, HttpResponse
from django.core import serializers
from django.views.generic import View
from django.views.generic import TemplateView
from . import consumer
from .forms import WeatherModelForm
from .models import measure
ACCUWEATHER = 'accuweather'
NOAA = 'noaa'
WEATHERDOTCOM = 'weatherdotcom'
def CreateWeather(request):
form = WeatherModelForm(request.GET or None)
if form.is_valid():
form.save()
form = WeatherModelForm()
return redirect('/search')
context = {'form':form}
return render(request, 'main/formulario.html', context)
class SearchWeather(View):
def get_avg_temperature(self, temperatures):
# Calculate avarage current temperatures at the service weather
return round(sum(temperatures) / len(temperatures), 4)
def get_data_accuweather(self, **kwargs):
# Current Temperatures at the service Accuweather
service = ACCUWEATHER
latitude, longitude = kwargs.get('latitude'), kwargs.get('longitude')
params = 'q={},{}'.format(latitude, longitude)
# Get Data with key Location
location_endpoint = 'http://127.0.0.1:5000/{}?{}&{}'.format(service, latitude, longitude)
data_response = consumer.consumer_api(service, location_endpoint)
data_temperature = data_response.get('simpleforecast')[0].get('forecastday')
maximum = data_temperature.get('high').get('Value')
minimum = data_temperature.get('low').get('Value')
avg_temperature = self.get_avg_temperature([maximum, minimum])
unit = data_temperature.get('low').get('Unit')
data_temperature['Avg'] = {'Value': avg_temperature, 'Unit': unit}
return data_temperature
def get_data_noaa(self, **kwargs):
# Current Temperatures at the service Noaa
service = NOAA
latitude, longitude = kwargs.get('latitude'), kwargs.get('longitude')
location_endpoint = 'points/{},{}'.format(latitude, longitude)
# Get url convert CWA
url_data_response = consumer.consumer_api(service, location_endpoint).get('properties').get('forecastHourly')
# Get periods current weather
list_current_periods = consumer.request_url(url_data_response).get('properties').get('periods')
list_current_temperature = [p.get('temperature') for p in list_current_periods]
minimum = min(list_current_temperature)
maximum = max(list_current_temperature)
avg_temperature = self.get_avg_temperature(list_current_temperature)
unit = list_current_periods[0].get('temperatureUnit')
data_temperature = {
'Minimum': {'Value': minimum, 'Unit': unit},
'Maximum': {'Value': maximum, 'Unit': unit},
'Avg': {'Value': avg_temperature, 'Unit': unit},
}
return data_temperature
def get_data_weatherdotcom(self):
pass
def get(self, request, *args, **kwargs):
service = request.GET.get('service', None)
latitude = request.GET.get('latitude', None)
longitude = request.GET.get('longitude', None)
if service:
service = service.split(',')
if latitude:
latitude = float(latitude)
if longitude:
longitude = float(longitude)
required_data = {'service': service, 'latitude': latitude, 'longitude': longitude}
if service and latitude and longitude:
data = {}
# SERVICE ACCUWEATHER
if ACCUWEATHER in service:
data['ACCUWEATHER'] = self.get_data_accuweather(**required_data)
# SERVICE NOAA
if NOAA in service:
data['NOAA'] = self.get_data_noaa(**required_data)
# SERVICE WEATHERDOTCOM
if WEATHERDOTCOM in service:
data['WEATHERDOTCOM'] = self.get_data_weatherdotcom(**required_data)
# Avg between many services
avg_services = []
for k, d in data.items():
avg_services.append(data.get(k).get('Avg').get('Value'))
data['AVG_SERVICES'] = self.get_avg_temperature(avg_services)
status = 200 if data else 404 # Successfuly or Error
else:
status = 404
data_none = ', '.join([k for k,v in required_data.items() if v is None])
message = 'Does not especify: {}'.format(data_none)
data = {'status': 'false', 'message': message}
return JsonResponse(status=status, data=data, safe=False)
consumer.py
import requests
from django.conf import settings
def request_url(url):
data = {}
with requests.get(url) as response:
data = response.json()
return data
def consumer_api(service, endpoint, params=None):
service_endpoints = {
'accuweather': 'http://127.0.0.1:5000/{}?'.format(endpoint),
'noaa': 'https://api.weather.gov/{}'.format(endpoint),
}
# Get url and response json
url_get_endpoint = service_endpoints.get(service)
if params:
url_get_endpoint += '&' + params
return request_url(url_get_endpoint)
http://127.0.0.1:5000/accuweather?latitude=44&longitude=33
{ "simpleforecast": { "forecastday": [ { "period": 1, "high": { "fahrenheit": "68", "celsius": "20" }, "low": { "fahrenheit": "50", "celsius": "10" }, "current": { "fahrenheit": "55", "celsius": "12" }, "conditions": "Partly Cloudy", "icon": "partlycloudy", "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif", "skyicon": "mostlysunny", "pop": 0, "qpf_allday": { "in": 0.0, "mm": 0.0 } } ] } }