aws / chalice

Python Serverless Microframework for AWS
Apache License 2.0
10.67k stars 1.01k forks source link

Question: Websocket connection in chalice local #2007

Open sreenathan-nair opened 1 year ago

sreenathan-nair commented 1 year ago

I apologize if the question has already been asked before, I could not find anything substantial looking through the issues and docs. Is there a reference or minimal example which demonstrates how to connect to websocket when running chalice local?

Following is my setup, however I encounter errors when trying to connect to ws, only errors locally:

Enable and register websocket support and session

app = Chalice(app_name="testapp")
app.experimental_feature_flags.update(
    [
        "WEBSOCKETS",
    ]
)
app.websocket_api.session = boto3.Session()

# It doesn't get this far, but including below for completeness
@app.on_ws_message()
def _ws_message(event):
    return Response(
        {
            "message": "Success!",
        },
        status_code=200,
    )

Client code for connection

Working version (deployed)

url = "wss://####.execute-api.#####.amazonaws.com/api/"

async def connect():
    async with websockets.connect(
        url,
    ) as ws:
        print("Connected to the switch.")

if __name__ == "__main__":
    asyncio.run(connect())

Non-working version (chalice local)

url = "ws://localhost:8000/"

async def connect():
    async with websockets.connect(
        url,
    ) as ws:
        print("Connected to the switch.")

if __name__ == "__main__":
    asyncio.run(connect())

Error received for the above non-working version:

websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 200

From what I understand, it looks like the connection does not get upgraded properly in local mode. It just hits the "/" http route and accepts the response which is just a {"message": "OK"} in this case.

If someone could point me in the right direction, that'd be great!

Thank you for your help!

luisfontes19 commented 1 year ago

Did you manage to solve this?

I'm having similar issues

Ankushpandey-ti commented 1 year ago

same, i want to test chalice websockets locally facing issue with it

tipu commented 1 year ago

also interested in this.