V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
taomujian
V2EX  ›  Python

vue 和 fastapi websocket 通信时终端连接有延迟

  •  
  •   taomujian · 2021-11-16 16:55:46 +08:00 · 1972 次点击
    这是一个创建于 891 天前的主题,其中的信息可能已经有所发展或是发生改变。
    当前端切换页面时发送断开请求,后端总是要过几秒才中断连接,在这期间前端新页面的请求会堵塞住,直到后端的 websocket 连接断开才会正常请求

    python:
    async def status(websocket: WebSocket):
    await websocket.accept()
    try:
    while True:
    request = await websocket.receive_json()
    response = {'code': '', 'message': '', 'data': ''}
    await websocket.send_json(response)
    time.sleep(5)
    except WebSocketDisconnect:
    print('关闭连接')
    await websocket.close()

    vue:
    destroyed() {
    this.websocket.close()
    },
    6 条回复    2021-11-16 18:21:24 +08:00
    jenlors
        1
    jenlors  
       2021-11-16 17:46:41 +08:00
    为什么有一个 time.sleep(5)?
    Latin
        2
    Latin  
       2021-11-16 17:53:06 +08:00
    好家伙 flask 转 fastapi 又来一道 哈哈
    Vegetable
        3
    Vegetable  
       2021-11-16 17:55:35 +08:00
    time.sleep 天秀,哪怕一定要用 sleep ,请用 asyncio.sleep
    vicalloy
        4
    vicalloy  
       2021-11-16 17:57:51 +08:00
    别在 async 里用同步函数,sleep 换成
    await asyncio.sleep(5)
    taomujian
        5
    taomujian  
    OP
       2021-11-16 18:21:01 +08:00
    @vicalloy 好的,感谢感谢
    taomujian
        6
    taomujian  
    OP
       2021-11-16 18:21:24 +08:00
    @long2ice 定时查询用的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3192 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:30 · PVG 21:30 · LAX 06:30 · JFK 09:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.