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

引入asyncio与httpx后Python步进调试器崩溃的问题

解决方案:无需等待响应的HTTP请求实现(规避VS Code调试器崩溃)

方案1:线程池异步发送请求(调试友好)

用Python标准库concurrent.futures.ThreadPoolExecutor,把同步HTTP请求放到后台线程执行,既不阻塞主线程,又不会触发调试器崩溃问题:

import requests
from concurrent.futures import ThreadPoolExecutor

# 初始化线程池,按需调整大小
executor = ThreadPoolExecutor(max_workers=5)

def send_async_request(url, data=None):
    # 提交任务到线程池,不等待结果返回
    executor.submit(requests.post, url, data=data)

# 在Django视图或业务逻辑中调用
send_async_request("https://example.com/webhook", data={"key": "value"})

方案2:调整VS Code调试配置兼容异步代码

尝试修改调试配置,关闭justMyCode或启用子进程调试,可能解决asyncio+httpx导致的调试器崩溃:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": ["runserver"],
            "django": true,
            "justMyCode": false,  // 关闭仅调试自身代码的限制
            "subProcess": true    // 启用子进程调试
        }
    ]
}

如果调整后调试器稳定,可继续使用httpx+asyncio实现无等待请求:

import asyncio
import httpx

async def send_async_request(url, data=None):
    async with httpx.AsyncClient() as client:
        # 发送请求后不等待响应,直接返回
        await client.post(url, data=data)

# 在Django中调用异步函数
asyncio.create_task(send_async_request("https://example.com/webhook", data={"key": "value"}))

方案3:轻量后台任务库

如果需要更持久的后台任务,可使用django-background-tasks这类轻量库,将HTTP请求作为后台任务执行,完全脱离主线程:

from background_task import background

@background(schedule=0)
def send_delayed_request(url, data=None):
    import requests
    requests.post(url, data=data)

# 调用后立即返回,任务在后台执行
send_delayed_request("https://example.com/webhook", data={"key": "value"})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:05:13