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

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统