【问题标题】:PyOWM and weather alertsPyOWM 和天气警报
【发布时间】:2021-05-29 00:59:00
【问题描述】:

我对 Python 编程很陌生。我正在尝试找出 PyOWM api,但我已经摸索过了。最大的问题是尝试使用 ONE_CALL 查找所有类名和值。我真的被困在从打开的天气图返回的 json 字符串中的天气警报上。阅读 pyown 文档,除了创建您自己的警报触发器之外,我没有看到任何其他参考。

在调用 one_call(lat,lon) 后使用 pyowm,它会从服务器获取响应,您可以通过并获取特定项目,例如 temp 和 wind,即

print(one_call.current.temperature.get('temp'))

我已经弄清楚如何获得每小时和每天的预报。

目前我们处于天气警报下,它显示在返回的 json 中,但我不知道如何让 pyowm 获得该警报。 PDF 的 one_call 部分非常缺乏它所公开的内容。至少对我来说是这样。就像我说我是 Python 新手,距离我做任何真正的编程已经 15 年了。曾经做过 VB6 和一些 C 和 C++,但仅此而已。

感谢您的帮助。

【问题讨论】:

    标签: python-3.x api openweathermap


    【解决方案1】:

    由于 pyOWM 是一个更复杂的 API 的包装器,因此可能他们没有实现 Open Weather API 的警报部分。 我尝试浏览他们的文档,甚至他们的代码库,但我找不到任何关于更改的参考。

    我建议使用包装器(因为它对于任何与警报无关的东西都更简单)并单独请求警报,如果这可以在您的用例中完成的话。 因此,在检查天气后,您可以执行以下操作:

    import requests
    
    # this is what returns your weather data, with the given parameters. 
    # note that we're excluding everything except alerts so that you only receive those
    API_ENDPOINT = "https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}".format(your_lat, your_lon, 'current,minutely,hourly,daily', your_api_key)
    
    # we call the endpoint to get alert info only
    alert_data = requests.get(API_ENDPOINT)
    
    # now let's check the HTTP status to make sure everything went right:
    if alert_data.status_code == 200:
        print(alert_data['alerts']
        # inside this variable there are all alerts
    else:
        print('some %s error occurred' % alert_data.status_code)
    

    根据 OWM 规范,alert_data 变量中的警报将具有 this 格式,因此它是一个字典列表:

    "alerts": [
        {
          "sender_name": "NWS Tulsa",
          "event": "Heat Advisory",
          "start": 1597341600,
          "end": 1597366800,
          "description": "...HEAT ADVISORY REMAINS IN EFFECT FROM 1 PM THIS AFTERNOON TO\n8 PM CDT THIS EVENING...\n* WHAT...Heat index values of 105 to 109 degrees expected.\n* WHERE...Creek, Okfuskee, Okmulgee, McIntosh, Pittsburg,\nLatimer, Pushmataha, and Choctaw Counties.\n* WHEN...From 1 PM to 8 PM CDT Thursday.\n* IMPACTS...The combination of hot temperatures and high\nhumidity will combine to create a dangerous situation in which\nheat illnesses are possible."
        },
        ...
      ]
    

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 2016-01-27
      • 1970-01-01
      • 2013-06-22
      • 2016-06-10
      相关资源
      最近更新 更多