背景介绍
网络通信项目是实现网络请求的基础模块,需要具备请求参数解析、状态码验证和错误提示展示等核心功能。本项目旨在模拟一个小型天气信息获取系统,通过HTTP请求接收参数并返回结果,同时处理常见错误状态码,确保系统的健壮性。
思路分析
- 请求参数解析
使用URL查询参数解析输入参数,例如:location=北京。参数可使用字典或请求对象的查询参数方式传递。 -
状态码处理
通过HTTP状态码200表示成功,404表示请求失败。需在请求中检查响应码,并在异常情况下展示错误信息。 -
错误提示展示
使用print语句或异常处理机制展示错误信息,例如:print("请求失败,状态码404")。
示例代码实现
import requests
def fetch_weather_info(location, units=None, lang=None):
"""
实现天气信息获取并返回响应
输入:location(字符串), units(单位,可选),lang(语言,可选)
输出:天气信息及状态码
"""
try:
# 构建请求URL
url = f'https://api.weatherapi.com/v1/stations.json?location={location}'
# 设置请求头
headers = {
'Content-Type': 'application/json',
'Lang': lang
}
# 设置请求方法
method = 'GET'
# 设置请求参数
params = {}
if units is not None:
params['units'] = units
if lang is not None:
params['lang'] = lang
# 发送请求
response = requests.request(method, url, headers=headers, params=params)
# 处理响应状态码
status_code = response.status_code
print(f"状态码: {status_code}")
# 处理响应数据
if status_code == 200:
print("成功获取天气信息,包含:")
print(f"气温: {response.json()['temperature']}°C")
print(f"湿度: {response.json()['humidity']}%%")
print(f"风速: {response.json()['windSpeed']} m/s")
else:
print("请求失败,状态码: 404")
except requests.exceptions.RequestException as e:
print("请求失败,状态码: 404")
print(f"错误信息: {str(e)}")
# 示例调用
fetch_weather_info("北京", units="metric", lang="zh-CN")
总结
本项目通过Python实现了网络通信的核心功能,包括天气信息的获取、状态码的验证以及错误信息的提示展示。关键点在于合理设计请求参数、状态码检查和异常处理机制,确保系统的健壮性和可维护性。通过示例代码,展示了各模块的实现细节,确保代码规范、可运行且具有解释性注释。