Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python api

作者:渚寒烟淡   发布日期:2026-03-19   浏览:39

# 示例代码:使用 Python 调用 API 并处理响应

import requests

def get_weather(city):
    # 定义 API 的 URL 和参数
    url = "http://api.weatherapi.com/v1/current.json"
    params = {
        'key': 'your_api_key_here',  # 替换为你的 API 密钥
        'q': city
    }

    # 发送 GET 请求
    response = requests.get(url, params=params)

    # 检查响应状态码
    if response.status_code == 200:
        data = response.json()
        # 解析并返回天气信息
        weather_info = {
            'temperature': data['current']['temp_c'],
            'condition': data['current']['condition']['text']
        }
        return weather_info
    else:
        return f"Error: Unable to fetch data. Status code: {response.status_code}"

# 示例调用
city = "London"
weather = get_weather(city)
print(f"Weather in {city}: {weather['temperature']}°C, {weather['condition']}")

解释说明:

  1. 导入 requests:用于发送 HTTP 请求。
  2. 定义 get_weather 函数:该函数接受一个城市名称作为参数,并调用天气 API 获取当前天气信息。
  3. 设置 API URL 和参数:包括 API 密钥和查询的城市名称。
  4. 发送 GET 请求:使用 requests.get 方法发送请求,并传递 URL 和参数。
  5. 检查响应状态码:如果状态码为 200,表示请求成功,解析 JSON 响应并提取所需信息;否则返回错误信息。
  6. 示例调用:调用 get_weather 函数并打印结果。

请确保你已经安装了 requests 库,可以通过以下命令安装:

pip install requests

上一篇:python批量注释

下一篇:python ui

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站