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

相关文章

selenium自动追踪微信小程序审核方案

小程序随着腾讯的不断推广,变的越来越普及,同时更新迭代的速度也越来越快,种类越来越多,那么在如何保证时效性就显得尤为重要,其中很重要一个环节就在于小程序审核通过之后,能否立刻通知到相关技术人员进行发布成为一件麻烦事,因为有些公司的发布权限在运营而非主要负责的开发人员手中,这时候就需要自动化测试工具出手了!     场景:A公司,有多个技术团队,每个团队已研发出多个小程序or小游戏,并不断

bimface 模型集成-后端(java)上传、发起转换、获取转换状态

目录 前言后端架构流程存储表结构全局工具类先根据appid, appsecret 生成accesstoken, 保存到自己的存储服务器。利用保存的 accesstoken 上传模型发起转换获取转换状态根据bimface文件ID获取模型viewtoken, 获取到viewtoken就可以利用前端浏览模型或图纸了 前言 之前没有注意官方有个sdk,然后自己就实现了这么个逻辑。建议

关于百度map API for Android的mobile ak 102错误

一共有三个sha1值需要比对: 第一个是 sha1值是http://developer.baidu.com/map/sdkandev-14.htm 里面获得的sha1值(包括里面的cmd和界面的两种获取sha1值得方法) 第二个是 sha1值是打包好apk文件中META-INF 文件夹的CERT.RSA中的sha1值。http://bbs.lbsyun.baidu.com/vi

Linux脚本重定向

Shell中可能经常能看到:>/dev/null  2>&1  eg:sudo kill -9 `ps -elf |grep -v grep|grep $1|awk '{print $4}'` 1>/dev/null 2>/dev/null 命令的结果可以通过%>的形式来定义输出 /dev/null 代表空设备文件 > 代表重定向到哪里,例如:echo "123" > /home/1

Linux下网卡开机自动加载

新安装的虚拟机发现自动起不了网卡接口,每次启动都要 # ifup ens33 则比较麻烦,将下面eht1改成自己的网卡名称的文件修改即可 编辑/etc/sysconfig/network-scripts/ifcfg-eth1 ONBOOT=yes

获取Xcode的安装包

前言 前段时间出现了 Xcode Ghosht 事件,所以担心第三方的xcode会被植入后门,最近要把xcode6.4升级到xcode7.0,刚好公司又限制了网速,从appstore更新xcode搞了两三天都没更新完,中途老是自动中止,更可恶的是更新期间不能使用xcode,简直是欲望无泪。唯一的办法只能从家里下载一个安装包,拷贝到公司的电脑上进行安装,但是从appstore上更新下来的就直接自动

Centos Mysql定时自动备份

一、备份准备&备份测试 1、备份目录准备 #mysql专用目录mkdir /mysql#mysql备份目录mkdir /mysql/backup#mysql备份脚本mkdir /mysql/backup/scripts#mysql备份文件mkdir /mysql/backup/files#mysql备份日志mkdir /mysql/backup/logs 2、备份脚本准备

spring boot中数据验证validated的使用

前言 spring-boot中在Controller层里面可以用@validated来校验数据再进入业务逻辑层,如果数据异常则会统一抛出异常,方便异常中心统一处理。 比如,我们判断一个输入的用户名长度限制以及密码的正则验证. 使用流程 1.Controller层数据使用@validated注解 @PostMapping("/userLogin")@ResponseBodypublic

微信摇一摇之获取设备与用户信息

一.前言 利用微信摇一摇的功能接口可实现我们日常的某些需求,比如微信摇一摇签到等。首先需要购买设备,然后在开发者后台创建应用以及绑定回调界面,回接下来就开始开发了。 二.开始 1.请求说明 Https请求方式: POST https://qyapi.weixin.qq.com/cgi-bin/shakearound/getshakeinfo?access_token=ACCESS_TOKE

微信企业号之获取access_token

一.前言 获取access_token是调用企业微信API接口的第一步,相当于创建了一个登录凭证,其它的业务API接口,都需要依赖于access_token来鉴权调用者身份。因此开发者,在使用业务接口前,要明确access_token的颁发来源,使用正确的access_token。 二.使用流程 请求方式: GET(HTTPS) 请求地址: https://qyapi.weixin.qq.c