基于高德 API 的自动获取气候数据的 Python 脚本

2024-05-05 07:28

本文主要是介绍基于高德 API 的自动获取气候数据的 Python 脚本,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 高德申请 Key
  • 脚本介绍
  • 运行结果示例

源代码: https://github.com/ma0513207162/PyPrecip。pyprecip\reading\read_api.py 路径下。

项目介绍:PyPrecip 是一个专注于气候数据处理的 Python 库,旨在为用户提供方便、高效的气候数据处理和分析工具。该库致力于处理各种气候数据,并特别关注于降水数据的处理和分析。

高德申请 Key

地址: https://lbs.amap.com/api/webservice/guide/api/weatherinfo在这里插入图片描述
个人申请 Key 很简单, 按照官方教程即可。

脚本介绍

导入相关的库和模块,用于支持程序的正常运行。包含自定义的异常抛出、警告、request请求、参数检查等。

import json
from requests.exceptions import RequestException 
from ..utits.http_ import send_request 
from ..utits.sundries import check_param_type
from ..utits.except_ import RaiseException as exc 
from ..utits.warn_ import RaiseWarn as warnWEATHER_KEY = ""

__check_weather_key 装饰器:检查全局变量 WEATHER_KEY 是否存在,如果不存在,打印相关提示。

# private decorator 
def __check_weather_key(func):def wrapper(*args, **kwargs):"""Check whether the global variable WEATHER_KEY is empty, and if it is, prompt the user to register a Web service API and assign a value."""if not WEATHER_KEY:print("\033[93m- PyPrecip Warning: \033[0mWEATHER_KEY is not set.")print("\033[0m- Please register for a Web Service API at\033[94m https://console.amap.com/dev/key/app.")print("\033[0m- After registering, set the value of the global variable 'read_api.WEATHER_KEY' like this:")print("\033[92m- read_api.WEATHER_KEY = 'your_api_key_here' \033[0m")return; return func(*args, **kwargs)return wrapper

get_address_info 函数:在区域名正确的前提下,用于获取输入区域名来获取该区域的相关信息。

@__check_weather_key
def get_address_info(address: str = "", city: str = None) -> dict:"""The Amap geocoding service API is encapsulated to obtain the region code based on the provided address information.Parameters------------------------------- address (str): The address information to obtain the corresponding region code- city (str): The city name, used to assist in obtaining the region code based on the addressReturns-------------------------------- dict: A dictionary containing the region code information based on the provided address- If the address parameter is empty or invalid, a ValueError exception is raised- If an error occurs during the request, a RequestException is raised"""check_param_type(address, str, "address"); check_param_type(city, str, "city")if address != "":with open("./pyprecip/_constant.json", "r", encoding="utf-8") as file:READ_API_DATA: dict = json.load(file)["READ_API"]    GEOCODING_URL: str = READ_API_DATA["GEOCODING_URL"]PARAMS: dict = { "key": WEATHER_KEY, "address": address,  "city": city}# 发送 request 请求 response = send_request(GEOCODING_URL, PARAMS)   address_info: dict = response.json()if address_info["status"] == "1" and address_info["infocode"] == "10000":if int(address_info["count"]) > 1:warn.raise_warning(f"The place name has multiple regional codes: {address}, the first one is selected by default.")return address_infoelse:except_address_info: str = address_info["info"]; exc.raise_exception(f"An unknown error occurred in the address request. {except_address_info} \Please try again later", RequestException)else:exc.raise_exception("address parameter cannot be null or invalid.", ValueError) 

get_weather_data 函数: 输入区域编码或区域名,来获取实时的气候数据。如果指定了 forecasts = True,则获取未来的气候数据。

@__check_weather_key
def get_weather_data(area_code: int = -1, address: str = "", city: str = "", forecasts: bool = False) -> dict:"""The Amap Open Platform weather data API is encapsulated to obtain real-time weather or future weather forecast data for a specified area.Parameters-------------------------------- area_code (int): indicates the region code. If provided, the region code is used to obtain weather data- address (str): indicates the address information. If the region code is provided but not provided, the region code is obtained based on the address- city (str): city name, used to assist in obtaining the area code based on the addressforecasts (bool): Specifies whether to obtain real-time weather data (False) or future weather forecast data (True)Returns-------------------------------- dict: A dictionary containing weather information for the requested area."""check_param_type(area_code, int, "area_code"); check_param_type(address, str, "address")check_param_type(city, str, "city")check_param_type(forecasts, bool, "forecasts")request_result: dict = {}with open("./pyprecip/_constant.json", "r", encoding="utf-8") as file:READ_API_DATA: dict = json.load(file)["READ_API"]    # 自动获取当前位置、根据地名获取区域编码 if area_code == -1 and address == "":# 自动获取当前的位置 URL: str = READ_API_DATA["LOCATION_URL"]PARAMS: dict = { "key": WEATHER_KEY }# 发送 request 请求 response = send_request(URL, PARAMS)            location_data: dict = response.json()if location_data["status"] == '1' and location_data["infocode"] == "10000":area_code = location_data["adcode"]request_result["area_code"] = location_data["adcode"]else:exc.raise_exception("An unknown error occurred with the ip location request. Please try again later", RequestException)elif area_code == -1 and address != "": address_info = get_address_info(address=address, city=city)area_code = address_info["geocodes"][0]["adcode"]request_result["area_code"] = area_codeelse:if address != "": warn.raise_warning("The area_code parameter overrides the effect of the address parameter.")request_result["area_code"] = area_code# 请求实时/未来的气候数据 WEATHER_URL = READ_API_DATA["WEATHER_URL"]ext_type = "base" if forecasts == False else "all" WEA_PARAMS = {"city": area_code,  "key": WEATHER_KEY, "extensions": ext_type}# 发送 http 请求response = send_request(WEATHER_URL, WEA_PARAMS)            weather_data = response.json()if weather_data["status"] == '1' and weather_data["infocode"] == '10000':if forecasts: forecasts_or_lives = weather_data["forecasts"][0]else:forecasts_or_lives = weather_data["lives"][0]forecasts_or_lives_copy = forecasts_or_lives.copy()for key_ in ["province", "city", "reporttime", "adcode"]:del forecasts_or_lives_copy[key_]forecasts_or_lives["casts"] = [forecasts_or_lives_copy]request_result["province"] = forecasts_or_lives["province"]request_result["city"] = forecasts_or_lives["city"]request_result["update_time"] = forecasts_or_lives["reporttime"] request_result["casts"] = forecasts_or_lives["casts"]return request_result                    else:exc.raise_exception("An unknown error occurred in the climate data request. Please try again later", RequestException)

运行结果示例

切换到 pyprecip 项目路径下,运行下面的命令。

python -m pyprecip.reading.read_api

指定区域编码:
在这里插入图片描述
指定区域名:
在这里插入图片描述

这篇关于基于高德 API 的自动获取气候数据的 Python 脚本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/961121

相关文章

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

Python打包成exe常用的四种方法小结

《Python打包成exe常用的四种方法小结》本文主要介绍了Python打包成exe常用的四种方法,包括PyInstaller、cx_Freeze、Py2exe、Nuitka,文中通过示例代码介绍的非... 目录一.PyInstaller11.安装:2. PyInstaller常用参数下面是pyinstal

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数

Python sys模块的使用及说明

《Pythonsys模块的使用及说明》Pythonsys模块是核心工具,用于解释器交互与运行时控制,涵盖命令行参数处理、路径修改、强制退出、I/O重定向、系统信息获取等功能,适用于脚本开发与调试,需... 目录python sys 模块详解常用功能与代码示例获取命令行参数修改模块搜索路径强制退出程序标准输入

Python pickle模块的使用指南

《Pythonpickle模块的使用指南》Pythonpickle模块用于对象序列化与反序列化,支持dump/load方法及自定义类,需注意安全风险,建议在受控环境中使用,适用于模型持久化、缓存及跨... 目录python pickle 模块详解基本序列化与反序列化直接序列化为字节流自定义对象的序列化安全注

Python之变量命名规则详解

《Python之变量命名规则详解》Python变量命名需遵守语法规范(字母开头、不使用关键字),遵循三要(自解释、明确功能)和三不要(避免缩写、语法错误、滥用下划线)原则,确保代码易读易维护... 目录1. 硬性规则2. “三要” 原则2.1. 要体现变量的 “实际作用”,拒绝 “无意义命名”2.2. 要让

python中的高阶函数示例详解

《python中的高阶函数示例详解》在Python中,高阶函数是指接受函数作为参数或返回函数作为结果的函数,下面:本文主要介绍python中高阶函数的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录1.定义2.map函数3.filter函数4.reduce函数5.sorted函数6.自定义高阶函数

利用Python操作Word文档页码的实际应用

《利用Python操作Word文档页码的实际应用》在撰写长篇文档时,经常需要将文档分成多个节,每个节都需要单独的页码,下面:本文主要介绍利用Python操作Word文档页码的相关资料,文中通过代码... 目录需求:文档详情:要求:该程序的功能是:总结需求:一次性处理24个文档的页码。文档详情:1、每个

Java发送SNMP至交换机获取交换机状态实现方式

《Java发送SNMP至交换机获取交换机状态实现方式》文章介绍使用SNMP4J库(2.7.0)通过RCF1213-MIB协议获取交换机单/多路状态,需开启SNMP支持,重点对比SNMPv1、v2c、v... 目录交换机协议SNMP库获取交换机单路状态获取交换机多路状态总结交换机协议这里使用的交换机协议为常