背景介绍
在现代网络开发中,合理记录请求状态及耗时信息是提升系统性能的关键。本项目旨在实现对URL或域名的HTTP请求状态码及请求时间的记录,适用于开发基础实践场景。通过Python的requests库,可独立运行并处理网络请求,同时结合文件读写与数据结构应用,实现高效开发。
思路分析
- 状态码解析:使用requests库获取响应对象的status_code属性
- 时间戳记录:通过time模块获取当前时间戳并保存记录
- 文件读写:在响应结果中读取内容并保存至本地文件(如
response_data.txt) - 异常处理:设置默认请求失败情况的处理逻辑
代码实现
import requests
import time
def record_request_info(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
response_data = response.text
timestamp = time.time() # 获取当前时间戳
print(f"请求成功 ({timestamp:.6f}s) -> 状态码 {response.status_code}")
with open("response_data.txt", "w") as f:
f.write(f"请求URL: {url}\n状态码: {response.status_code}\n时间: {timestamp:.6f}s")
print("请求完成,文件已记录")
return response.status_code
except requests.exceptions.RequestException as e:
print(f"请求失败 ({e}), 时间戳: {time.time():.6f}s")
return -1
# 示例调用
if __name__ == "__main__":
url_list = [
"https://example.com",
"https://api.example.com/data",
"https://www.google.com"
]
for url in url_list:
status_code, time_used = record_request_info(url)
print(f"请求 {url} 成功 ({time_used:.6f}s) -> 状态码 {status_code}")
总结
本项目通过Python的requests库实现了对网络请求状态码及耗时记录的自动化处理。代码实现了独立运行功能,结合文件读写,展示了网络请求基础实践的典型应用。项目要求符合学习价值高的技术实践标准,可帮助开发者提升开发效率并积累实践经验。通过本项目,不仅掌握了网络请求的核心机制,还学会了如何记录请求数据,具有良好的技术迁移价值。