question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

websocket for an ASGI server?

See original GitHub issue

Hello, I’m started to work with starlette. And like they say:

Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high performance asyncio services.

but with ocpp we need the standard websocket library, so I’m searching on what part of websocket library are in use with ocpp and the only two functions that I’m found are recv and send so I did writing an interface to satisfy this with starlette-websocket:

# websocketInterface.py file
from starlette.websockets import WebSocket

class WebSocketInterface():
    def __init__(self, websocket: WebSocket):
        self._websocket = websocket

    async def recv(self):
        receive_msg = await self._websocket.receive_text()
        return receive_msg

    async def send(self, text_message):
        await self._websocket.send_text(text_message)

now this object can be use like an standard websocket object, for example:

# simple starlette server.py file
import asyncio

from starlette.applications import Starlette

from websocketInterface import WebSocketInterface
from central_system import on_connect


app = Starlette()


@app.websocket_route('/{client_id:path}')
async def websocket_handler(websocket):
    interface = WebSocketInterface(websocket)

    await websocket.accept(subprotocol='ocpp1.6')
    await on_connect(interface, websocket.path_params['client_id'])
    await websocket.close()

this is with blob/master/examples/v16/central_system.py. Finally we can run this app with all python ASGI server (for example uvicorn):

myuser@mymachine:~: uvicorn --port 9000 server:app

What do you think? with some like this you could user straightforward all ASGI frameworks?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:11 (5 by maintainers)

github_iconTop GitHub Comments

5reactions
lsaavedrcommented, Jul 25, 2020

A more complete interface with close and exceptions:

# websocketInterface.py
from starlette.websockets import WebSocket, WebSocketDisconnect
from websockets.exceptions import ConnectionClosed

# transform starlette websocket to standard websocket
class WebSocketInterface():
    def __init__(self, websocket: WebSocket):
        self._websocket = websocket

    async def recv(self) -> str:
        try:
            return await self._websocket.receive_text()
        except WebSocketDisconnect as e:
            raise ConnectionClosed(e.code, 'WebSocketInterface')

    async def send(self, msg: str) -> None:
        await self._websocket.send_text(msg)

    async def close(self, code: int, reason: str) -> None:
        await self._websocket.close(code)

regards!

4reactions
OrangeTuxcommented, Jun 15, 2020

Thanks for your effort @lsaavedr!

This library tries not to be coupled to a specific implementation of websockets. Exactly for this reason: that you choose whatever implementation you want.

You correctly figured out that a websocket implementation should implement following interface:

  • ~async def recv() -> bytes~ async def recv() -> str
  • ~async def send(msg: bytes)~ async def send(msg: str)

As you’ve shown it’s easy to create a small wrapper around a websocket implementation which API is slightly different. In fact I’ve used this library successfully with Quart.

I think your code can be part of the documentation. What do you think?

Read more comments on GitHub >

github_iconTop Results From Across the Web

HTTP & WebSocket ASGI Message Format - Read the Docs
The HTTP+WebSocket ASGI sub-specification outlines how to transport HTTP/1.1, HTTP/2 and WebSocket connections within ASGI. It is deliberately ...
Read more >
How to Add Websockets to a Django App without Extra ...
It's the spiritual successor to WSGI, which has been used by frameworks like Django and Flask for a long time. ASGI lets you...
Read more >
Hello, ASGI - Encode
ASGI directly supports WebSockets, allowing developers to build more responsive web applications, and other highly interactive services that are not well suited ...
Read more >
A curated list of awesome ASGI servers, frameworks ... - GitHub
Daphne - An HTTP, HTTP2 and WebSocket protocol server for ASGI, developed to power Django Channels. · Hypercorn - An ASGI server based...
Read more >
WebSocket - BlackSheep - Neoteroi Docs
BlackSheep is able to handle incoming WebSocket connections if you're using an ASGI server that supports WebSocket protocol (for example ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found