Django网络应用开发的5项基础核心技术包括模型(Model)的设计,URL 的设计与配置,View(视图)的编写,Template(模板)的设计和Form(表单)的使用。
实现了用户自主添加应用后,需要完善各个应用功能,天气查询应用,星座和股票资讯信息应用。通过外部接口API请求数据,再把解析到的数据渲染到小程序的应用。
一、天气数据解析
外部API获取到的天气数据需要将json数据格式中的键值提取出来,再返回给小程序指定的天气数据。
import datetime
class CommonWeatherResult:
def __init__(self):
# 温度
self.temperature = None
# 风向
self.wind_direction = None
# 风强度
self.wind_strength = None
# 湿度
self.humidity = None
self.time = None
def __str__(self):
s = []
s.append("温度:%s" % self.temperature)
s.append("风向:%s" % self.wind_direction)
s.append("风强度:%s" % self.wind_strength)
s.append("湿度:%s" % self.humidity)
s = "\r\n".join(s)
s += ("\r\n")
return s
def to_dict(self):
result = {}
result["temperature"] = self.temperature
result["wind_direction"] = self.wind_direction
result["wind_strength"] = self.wind_strength
result["humidity"] = self.humidity
result["time"] = self.time if self.time else datetime.datetime.now()
return result
二、天气数据获取
通过 和风天气API 提供的天气数据,可以得到需要的数据。
和风天气 http://www.heweather.com/
import json
import requests
from thirdparty.weather import CommonWeatherResult
class HeWeather:
key = '23141d14264444899475aa5f0267b8b1'
weather_api = 'https://free-api.heweather.com/s6/weather/now'
@classmethod
def get_weather(cls, cityname, timeout=1):
weather_result = CommonWeatherResult()
location = cityname
params = list()
# 请求接口拼接
params.append("key=%s" % HeWeather.key)
params.append("location=%s" % location)
params = "&".join(params)
url = HeWeather.weather_api + "?" + params
# 获取某个城市的天气数据
response = requests.get(url, timeout=timeout)
text = response.text
# 获取请求响应的文本
if not text:
print("request error!")
# 反序列化
result = json.loads(text)
# 根据接口返回示例提取温度、湿度、风向、风级
now = result.get("HeWeather6")[0].get("now")
weather_result.temperature = now.get("tmp")
weather_result.wind_direction = now.get("wind_dir")
weather_result.humidity = now.get("hum") + "%"
weather_result.wind_strength = now.get("wind_sc") + "级"
return weather_result
if __name__ == "__main__":
result = HeWeather.get_weather("长沙市")
print(result)