Python weather app tutorial

import datetime as dt
import requests
"""
处理HTTP请求是在Web开发和许多网络应用中常见的任务
尤其是当需要与外部服务或API进行交互时。
python通过多个库提供了处理HTTP请求的功能
最著名且友好的是‘requests’库,以下是‘requests’库处理HTTP请求的一些基础知识

1.安装‘requests’库
通过运行以下命令
pip install requests

2.发送请求
‘requests’库支持多种HTTP请求方法,如GET,POST,PUT,DELETE等
最常用的是GET和POST
发送GET请求
GET请求通常用于请求数据。以下是一个发送GET请求的例子
import requsets
url = 'https://...'
response = requests.get(url)
#检查请求是否成功
if response.status_code == 200:
    #处理响应内容
    data = response.json
    print(data)
else:
    print('Failed to retrive data:',response.status_code)
    
发送POST请求
POST请求通常用于提交数据
import requests
url = 'https:...'
my_data = {'key':'value'}

response = requests.post(url,data = my_data)

if(response.status_code == 200:
    print('Data submitted successfully.')
else:
    print('Failed to submit data::'response.status_code)
    
3.响应处理
当发送一个请求后,‘requests’库会返回一个‘response’对象,其中包含了请求的结果
主要属性和方法包括:
'status_code':HTTP状态码,如200表示成功,404表示未找到等
'text':响应内容的字符串形式
'json()':如果响应是JSON格式,可以通过这个方法将其解析为python字典
'headers':一个字典,包含响应头

4.处理异常
在网络请求中,很多事情可能出错,如网络问题、错误的URL、服务不可用等。
requests库提供了一系列异常来帮助处理这些问题:
import requests
from requests.exceptions import HTTPError

url = 'https...'
try:
    response = requests.get(url)
    # 如果响应不是200,将引发异常
    response.raise_for_status()
except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')
else:
    print('Success!')

"""

BASE_URL = "http://API.openweathermap.org/data/2.5/weather?"
#API_KEY = open('api_key','r').read()
#API_KEY = "..."
# 打开文件,读取API密钥,然后立即关闭文件
with open('E:\\Python\\pycode\\PythonLearn\\api_key.txt', 'r') as file:
    API_KEY = file.read().strip()

CITY = "New York"


def kelvin_to_celsius_fahrenheit(kelvin):
    celsius = kelvin - 273.15
    fahrenheit = celsius * (9/5) + 32
    return celsius,fahrenheit

url = BASE_URL + "appid=" + API_KEY + "&q=" + CITY

response = requests.get(url).json()

"""
JSON是Web API 常用的数据格式。python的‘json’模块提供了简单的方法来解析JSON字符串
让它们编程python的数据结果(比如字典和列表)
1.使用json.loads()
json.loads()函数用于将JSON格式的字符串转换为Python的数据结构。
"loads"是"load string"的缩写,意为从字符串加载JSON数据。

假设从Web API获取了以下JSON格式的字符串:
{
  "name": "Jane Doe",
  "age": 25,
  "isEmployed": true,
  "skills": ["Python", "Data Analysis", "Machine Learning"],
  "address": {
    "street": "456 Elm St",
    "city": "Springfield",
    "zipCode": "12345"
  }
}
这个JSON对象包含了不同类型的数据:字符串、数字、布尔值、数组和嵌套的对象。

2.解析JSON字符串
要在Python中解析这个JSON字符串,
可以使用json.loads()方法:
import json

# 假设json_string变量包含了上面的JSON数据
json_string = '''
{
  "name": "Jane Doe",
  "age": 25,
  "isEmployed": true,
  "skills": ["Python", "Data Analysis", "Machine Learning"],
  "address": {
    "street": "456 Elm St",
    "city": "Springfield",
    "zipCode": "12345"
  }
}
'''

# 解析JSON字符串
data = json.loads(json_string)

# 现在data是一个Python字典
print(data['name'])  # 输出: Jane Doe
print(data['skills'])  # 输出: ['Python', 'Data Analysis', 'Machine Learning']
print(data['address']['city'])  # 输出: Springfield
在这个例子中,json.loads()将JSON字符串转换成了一个Python字典。
这使得可以使用标准的字典访问方法来获取数据。
例如,data['name']会获取name键对应的值。

3.处理不同的数据类型
JSON中的数据会被转换成Python的列表,
所以可以使用列表的索引和遍历方法来访问它们
同样,JSON对象中的嵌套对象也会被转换成字典,我们可以通过键来访问嵌套的数据
"""

"""
API(应用程序编程接口)是一种软件间交互的方式
允许不同的程序通过明确定义的方法相互通信。
API定义了请求的构造方式,可用的功能,数据格式以及如何访问这些功能。
在Web开发中,API通常指的是Web API,它允许应用程序通过互联网使用HTTP协议请求数据或功能。

1.使用API密钥进行认证
很多API为了控制访问权限,限制请求次数,或收集使用统计信息,需要使用API密钥进行认证
API密钥是一个唯一的标识符,我们需要在发起请求时提供这个密钥,以验证身份或访问权限。
通常,需要在API提供者的网站上注册,然后创建一个应用或项目来获取API密钥。
获取API密钥后,通常会在HTTP请求的头部(Header)中加入这个密钥,或者作为URL的一部分。
具体方法取决于API的设计。
示例:使用API发送请求
假设有一个天气API,其文档指出:

基础URL为https://api.weatherapi.com/v1/
使用API密钥进行认证,密钥应在查询参数中以key提供
获取当前天气的路径为current.json
必须的查询参数有key(API密钥)和q(查询位置,如城市名或邮编)
基于以上信息,一个请求当前天气的URL可能如下:

https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London

使用requests库发送这个请求的Python代码示例:
import requests

url = "https://api.weatherapi.com/v1/current.json"
params = {
    "key": "YOUR_API_KEY",
    "q": "London"
}

response = requests.get(url, params=params)
weather_data = response.json()

print(weather_data)
"""

 

import datetime as dt
import requests
BASE_URL = "http://API.openweathermap.org/data/2.5/weather?"
#API_KEY = open('api_key','r').read()
#API_KEY = "..."
# 打开文件,读取API密钥,然后立即关闭文件
with open('E:\\Python\\pycode\\PythonLearn\\api_key.txt', 'r') as file:
    API_KEY = file.read().strip()

CITY = "New York"


def kelvin_to_celsius_fahrenheit(kelvin):
    celsius = kelvin - 273.15
    fahrenheit = celsius * (9/5) + 32
    return celsius,fahrenheit

url = BASE_URL + "appid=" + API_KEY + "&q=" + CITY

response = requests.get(url).json()
temp_kelvin = response['main']['temp']
temp_celsius, temp_fahrenheit = kelvin_to_celsius_fahrenheit(temp_kelvin)
feels_like_kelvin = response['main']['feels_like']
feels_like_celsius, feels_like_fahrenheit = kelvin_to_celsius_fahrenheit(feels_like_kelvin)
wind_speed = response['wind']['speed']
humidity = response['main']['humidity']
description = response['weather'][0]['description']
sunrise_time = dt.datetime.utcfromtimestamp(response['sys']['sunrise'] + response['timezone'])
sunset_time = dt.datetime.utcfromtimestamp(response['sys']['sunset'] + response['timezone'])

#摄氏度符号 按住alt键,输入度符号0176
print(f"Temperature in {CITY}: {temp_celsius:.2f}°C or {temp_fahrenheit:.2f}°F")
print(f"Temperature in {CITY} feels like: {feels_like_celsius:.2f}°C or {feels_like_fahrenheit:.2f}°F")
print(f"Humidity in {CITY}: {humidity}%")
print(f"Wind Speed in {CITY}: {wind_speed}m/s")
print(f"General Weather in {CITY}: {description}")
print(f"Sun rises in {CITY} at {sunrise_time} local time.")
print(f"Sun sets in {CITY} at {sunset_time} local time.")

知识点:

URL(Uniform Resource Locator,统一资源定位符)是互联网上用于标识资源位置的一种引用或地址。它是Web上标准的资源定位方式,使得用户可以通过指定的地址访问互联网上的文档、图片、视频以及其他资源。URL具有标准格式,通常包含以下几个部分:

协议(Scheme):指明了用于访问资源的协议类型。常见的协议包括http(超文本传输协议)、https(安全的http)、ftp(文件传输协议)等。

主机名(Host):资源所在的服务器的域名或IP地址。

端口号(Port):可选部分,指明了服务器上特定的端口号,用于访问资源。如果未指定,将使用协议的默认端口(例如,HTTP的默认端口是80,HTTPS的默认端口是443)。

路径(Path):指向服务器上资源的具体位置。例如,在一个Web服务器上,路径可能指向一个特定的网页或图片。

查询字符串(Query):可选部分,以?开头,后面跟一系列的参数,这些参数通常用于向服务器发送额外的信息或请求。参数以key=value的形式出现,多个参数之间用&分隔。

片段(Fragment):可选部分,以#开头,用于指向资源内部的一个锚点(例如,网页中的特定位置)。

URL示例:

https:协议(Scheme)
www.example.com:主机名(Host)
443:端口号(Port),这里是HTTPS的默认端口,通常可以省略
/path/to/page.html:路径(Path),指向服务器上的一个资源
?query=value:查询字符串(Query),用于发送额外的信息给服务器
#section:片段(Fragment),指向网页内部的一个锚点
URL使得访问网络资源变得简单直接,通过在浏览器地址栏输入URL,用户可以直接访问到互联网上的各种资源。
 

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-14 23:38:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-14 23:38:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-14 23:38:03       82 阅读
  4. Python语言-面向对象

    2024-02-14 23:38:03       91 阅读

热门阅读

  1. 简单的手指控制机械臂

    2024-02-14 23:38:03       65 阅读
  2. 数据分析 — Pandas 数据处理

    2024-02-14 23:38:03       43 阅读
  3. Sublime Text 常用快捷键简介

    2024-02-14 23:38:03       50 阅读
  4. 飞机大作战(c语言)

    2024-02-14 23:38:03       51 阅读
  5. Spring中 Bean 的六种作用域官方说明

    2024-02-14 23:38:03       48 阅读