The server in the backend is built with aiohttp
using asyncio
. The client in the frontend is built using socket.io-client
in React. The server attempts to emit stock prices every minute, while the client fetch and display those prices in React.
server.py
import aiohttp
from aiohttp import web
import socketio
import asyncio
import contextlib
sio = socketio.AsyncServer(async_mode='aiohttp', logger=True, engineio_logger=True, cors_allowed_origins='*')
app = web.Application()
sio.attach(app)
url = 'https://financialmodelingprep.com/api/v3/stock/real-time-price?apikey=r9ihqzy4buIj0soQxeLmzhDxHvCVQc59'
async def server(request):
return web.Response(text='Server Running...')
async def get_prices():
async with aiohttp.ClientSession() as sess:
while True:
async with sess.get(url) as resp:
data = await resp.json()
await sio.emit('stocks', {'data': data['stockList']}, namespace='/prices')
await sio.sleep(60)
async def run_prices_loop(_app):
task = asyncio.create_task(get_prices())
yield
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task # Ensure any exceptions etc. are raised.
app.router.add_static('/static', 'static')
app.router.add_get('/', server)
app.cleanup_ctx.append(run_prices_loop)
if __name__ == '__main__':
web.run_app(app, host='127.0.0.1', port=8080)
client.js
import { io } from 'socket.io-client';
const URL_ = 'http://127.0.0.1:8080/prices';
export const socket = io.connect(URL_, {
cors: {
origin: 'http://127.0.0.1:8080',
credentials: true,
}
});
The error message whenever a client connect to the server to fetch the emitted prices:
emitting event "stocks" to all [/prices]
XzZjhwUKeocr4u9nAAAA: Sending packet OPEN data {'sid': 'XzZjhwUKeocr4u9nAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
XzZjhwUKeocr4u9nAAAA: Received packet MESSAGE data 0/prices,
XzZjhwUKeocr4u9nAAAA: Sending packet MESSAGE data 4/prices,"Unable to connect"
XzZjhwUKeocr4u9nAAAA: Received request to upgrade to websocket
XzZjhwUKeocr4u9nAAAA: Received packet CLOSE data
service task canceled