简介
这次要实现的是一个普通的网页卡片组件,用于显示访问ip所在城市的基本天气信息,用处不大,我的初心就是给我的网站首页充充门面的。由于本站前端是基于VUE3,那么本例也是如此。后端部分涉及到的第三方比较多,但还是基于DRF的
接口实现流程
- 首先需要再和风天气官网注册账户,创建你的项目并拿到你专属的key,没关系,我们可以用免费订阅
- 收集你前端要用到的各种天气图标图片资源,我是在和风天气官网中简单的找了一些用于我的项目。
- 在settings.py中配置你的url,方便后续在接口中直接调用(当然也可以不在settings.py中配置,直接写在view.py中一样的,个人习惯问题)
# 和风天气KEY
WEATHER_KEY = '你的key'
# 携带经纬度参数,获取实时天气
WEATHER_NOW_URL = 'https://devapi.qweather.com/v7/weather/now?&key='+WEATHER_KEY
# 携带经纬度参数,获取城市信息
WEATHER_GEO_URL = 'https://geoapi.qweather.com/v2/city/lookup?&key='+WEATHER_KEY
- 创建你的DRF天气获取接口,并在代码中获取请求的IP
# 别忘了导包
import requests
import json
import gzip
import urllib.request # 请求接口
import urllib.parse # 返回体解析
from loguru import logger # 日志用
from rest_framework import generics, viewsets, filters, status
"""
和风天气请求
"""
class WeatherView(generics.GenericAPIView):
def get(self, request, *args, **kwargs):
"""
通过请求IP获取经纬度, 再通过和风天气接口获取城市和天气信息
"""
source_ip = request.META.get('REMOTE_ADDR') # DRF中可以通过这中方式获取请求IP
logger.debug('访问者IP:'+source_ip)
- 获取请求IP的经纬度信息(如果是本机localhost地址,那就通过设定的默认经纬度【杭州】发送天气请求)
coordinate = '120.2052639863281,30.231124817451985' # 这个是杭州经纬度,默认设置
if source_ip != '127.0.0.1':
# 当不是本机发送的请求(开发过程),通过ip-api网站接口携带前端请求ID获取经纬度信息
response = json.loads(requests.get('http://ip-api.com/json/'+source_ip).text)
coordinate = str(response['lon']) + ',' + str(response['lat'])
# 携带经纬度信息请求和风天气的GEO接口
# 这个接口返回的是城市信息
geo_url = settings.WEATHER_GEO_URL + '&' + urllib.parse.urlencode({
'location': coordinate})
geo_requests = urllib.request.Request(geo_url)
- 请求天气信息
weather_url = settings.WEATHER_NOW_URL + '&' + urllib.parse.urlencode({
'location': coordinate})
weather_requests = urllib.request.Request(weather_url)
- 读取天气和城市请求的返回体信息
try:
with urllib.request.urlopen(geo_requests) as response:
# 检查响应是否是gzip压缩的
if response.headers.get('Content-Encoding') == 'gzip':
# 使用gzip解压响应内容
compressed_data = response.read()
with gzip.GzipFile(fileobj=io.BytesIO(compressed_data)) as gzip_file:
decompressed_data = gzip_file.read()
GEO_RES = decompressed_data.decode('utf-8') # 解码为utf-8字符串
else:
# 如果没有gzip压缩,直接读取并解码
GEO_RES = response.read().decode('utf-8')
logger.debug('城市信息:'+GEO_RES)
with urllib.request.urlopen(weather_requests) as response:
# 检查响应是否是gzip压缩的
if response.headers.get('Content-Encoding') == 'gzip':
# 使用gzip解压响应内容
compressed_data = response.read()
with gzip.GzipFile(fileobj=io.BytesIO(compressed_data))<