基于高德 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

相关文章

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提