You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python控制台应用中调用Django REST API并显示响应?

在Python控制台访问Django REST API的方法

作为新手,你可以用以下两种简单方式在Python控制台中调用你的Django REST API并查看响应:

方法一:使用requests库(推荐,语法简洁)

这是Python中处理HTTP请求最常用的库,先安装它:

pip install requests

然后编写控制台代码,根据你的API类型(GET/POST等)发送请求:

import requests

# 替换为你的Django API实际端点URL
API_URL = "http://localhost:8000/api/your-resource/"

# 发送GET请求获取数据
response = requests.get(API_URL)

# 检查请求是否成功
if response.status_code == 200:
    # 解析JSON格式的响应
    response_data = response.json()
    print("API返回数据:")
    print(response_data)
else:
    print(f"请求失败,状态码:{response.status_code}")

# 如果需要发送POST请求提交数据
post_payload = {"name": "test", "description": "sample data"}
post_response = requests.post(API_URL, json=post_payload)
if post_response.status_code in [200, 201]:
    print("\nPOST请求成功,返回数据:")
    print(post_response.json())
else:
    print(f"\nPOST请求失败,状态码:{post_response.status_code}")

方法二:使用Python内置urllib库(无需额外安装)

如果不想安装第三方库,可以用Python自带的urllib模块:

import urllib.request
import json

API_URL = "http://localhost:8000/api/your-resource/"

# 发送GET请求
try:
    with urllib.request.urlopen(API_URL) as response:
        # 读取并解码响应内容
        raw_data = response.read().decode("utf-8")
        # 解析为JSON对象
        parsed_data = json.loads(raw_data)
        print("API返回数据:")
        print(parsed_data)
except urllib.error.HTTPError as e:
    print(f"请求失败,状态码:{e.code}")
except urllib.error.URLError as e:
    print(f"连接出错:{e.reason}")

关键注意事项

  • 确保你的Django开发服务器正在运行(执行python manage.py runserver启动)
  • 如果你的API需要认证(比如Token认证),要在请求头中添加认证信息:
    以requests为例:
    headers = {"Authorization": "Token your-token-value"}
    response = requests.get(API_URL, headers=headers)
    
  • 如果API返回的不是JSON格式,直接用response.text(requests)或raw_data(urllib)打印原始响应内容即可

内容的提问来源于stack exchange,提问作者user369287

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:50:33