Skip to content
Snippets Groups Projects
Commit b4bc62c3 authored by Vincent Texier's avatar Vincent Texier
Browse files

[fix] #58 fix request_web_socket_block example

parent 9e532d2c
No related branches found
No related tags found
No related merge requests found
Pipeline #7078 failed
import asyncio import asyncio
import json
from _socket import gaierror from _socket import gaierror
import aiohttp import aiohttp
import jsonschema import jsonschema
from duniterpy.api import bma from duniterpy.api import bma
from duniterpy.api.client import Client, parse_text from duniterpy.api.client import Client
# CONFIG ####################################### # CONFIG #######################################
...@@ -26,35 +27,16 @@ async def main(): ...@@ -26,35 +27,16 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
try: try:
# Create Web Socket connection on block path # Create Web Socket connection on block path (async method)
ws_connection = client(bma.ws.block) ws = await client(bma.ws.block) # Type: WSConnection
# From the documentation ws_connection should be a ClientWebSocketResponse object...
#
# https://docs.aiohttp.org/en/stable/client_quickstart.html#websockets
#
# In reality, aiohttp.session.ws_connect() returns a aiohttp.client._WSRequestContextManager instance.
# It must be used in a with statement to get the ClientWebSocketResponse instance from it (__aenter__).
# At the end of the with statement, aiohttp.client._WSRequestContextManager.__aexit__ is called
# and close the ClientWebSocketResponse in it.
# Mandatory to get the "for msg in ws" to work !
async with ws_connection as ws:
print("Connected successfully to web socket block path") print("Connected successfully to web socket block path")
# Iterate on each message received...
async for msg in ws: data = await ws.receive_json()
# if message type is text...
if msg.type == aiohttp.WSMsgType.TEXT: jsonschema.validate(data, bma.ws.WS_BLOCK_SCHEMA)
print("Received a block") print("Received a block")
# Validate jsonschema and return a the json dict print(json.dumps(data, indent=2))
block_data = parse_text(msg.data, bma.ws.WS_BLOCK_SCHEMA)
print(block_data)
elif msg.type == aiohttp.WSMsgType.CLOSED:
# Connection is closed
print("Web socket connection closed !")
elif msg.type == aiohttp.WSMsgType.ERROR:
# Connection error
print("Web socket connection error !")
# Close session # Close session
await client.close() await client.close()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment