Ожидаемое сообщение ASGI ‘websocket.accept’ или ‘websocket.close’, но получил ‘http.response.start’

#python #reactjs #websocket #fastapi #python-socketio

#питон #reactjs #веб- сокет #fastapi #python-socketio

Вопрос:

Я хочу подключиться websockets , но при запуске получаю сообщение об ошибке.

uvicorn app:app --reload --ws websockets

требования

  • ОС: Linux Ubuntu 20.04 LTS
  • Python 3.8.6
  • Браузер: Chrome 88.0.4324.182
  • fastapi == 0.63.0
  • python-engineerio == 4.0.0
  • python-socketio == 5.0.4
  • starlette == 0.13.6
  • uvicorn == 0.13.3
  • websockets == 8.1

app.py

 from typing import Optional

import socketio
from fastapi import FastAPI, Query, WebSocket


sio = socketio.AsyncServer(
    async_mode="asgi", cors_allowed_origins="*", logger=True, engineio_logger=True
)
app = FastAPI(debug=True)
app_socketio = socketio.ASGIApp(sio)
app.mount(path="/", app=app_socketio)


@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
    websocket: WebSocket,
    item_id: str,
    q: Optional[int] = None,
):
    # pylint: disable=C0103,W0613
    await websocket.accept()
    while True:
        data: str = await websocket.receive_text()
 

react-приложение

 const Index: React.FC = () => {
    var ws = new WebSocket('ws://127.0.0.1:8000/items/1/ws')
}
 

Трассировка

 Traceback (most recent call last):
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 157, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/middleware/errors.py", line 146, in __call__
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/starlette/routing.py", line 376, in handle
    await self.app(scope, receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/engineio/async_drivers/asgi.py", line 65, in __call__
    await self.not_found(receive, send)
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/engineio/async_drivers/asgi.py", line 110, in not_found
    await send({'type': 'http.response.start',
  File "/home/m0nte-cr1st0/.virtualenvs/hypercube/lib/python3.8/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 209, in asgi_send
    raise RuntimeError(msg % message_type)
RuntimeError: Expected ASGI message 'websocket.accept' or 'websocket.close', but got 'http.response.start'.
 

Ответ №1:

 const Index: React.FC = () => {
var ws = new WebSocket('ws://127.0.0.1:8000/items/1/ws')
 

}

сделайте эту функцию асинхронной и ждите и повторите попытку