def __init__(self, host=None, port=None, sub_topic=None, loop=None, **kwargs): self.logger = setup_logger(__name__) self.loop = loop or asyncio.get_event_loop() self.host = host self.port = port self.sub_topic = sub_topic self.tasks = [] for signum in [signal.SIGTERM, signal.SIGINT]: self.loop.add_signal_handler(signum, self.shutdown)
def __init__(self, **kwargs): super().__init__(**kwargs) self.tasks = [] self.logger = setup_logger(__name__) # the fact, that the connection state resides in the process memory # implies usage of [--workers 1] parameter of gunicorn or running # without gunicorn altogether ) # if one intends to use many workers, # the global game (room, connection, id) state has to be shared between workers # via redis e.g., that's more complex structure for this simple application # # at current state the total set of available nyms is shared via redis # by this web.Application and its worker processes self.state = HXApplicationState(self.logger) self.on_startup.append(self._setup) self.on_shutdown.append(self._on_shutdown_handler)
import sys sys.path.append(os.getcwd()) import telebot import tlgrm_secrets from websockets_server.core.settings import HENDRIX_CHANNEL, REDIS_HOST, REDIS_PORT from websockets_server.core.message_proto_handler import MessageProtoHandler from utils.log_helper import setup_logger import redis import json bot = telebot.AsyncTeleBot(tlgrm_secrets.token2) r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) logger = setup_logger(__name__, filename_arg='tlgrm_listen_hendrix') command = 'send' @bot.message_handler(content_types=["text"], commands=['send']) def forward_messages(message): logger.debug('debug [%s]: [%s]', HENDRIX_CHANNEL, message) if message.from_user.id == tlgrm_secrets.chat_id: logger.info('[%s]: [%s]', HENDRIX_CHANNEL, message.text) try: suffix = message.text[len(command) + 1:] ws_id, text = suffix.split('|')[:2] ws_id = ws_id.strip() text = 'PPP: ' + text.strip() except Exception as e:
from unittest.mock import patch, Mock, AsyncMock, call, MagicMock, ANY from websockets_server.core.server import HXApplication, nyms, HXApplicationState import websockets_server from websockets_server.core import message_proto_handler from websockets_server.core.settings import ROUNDTRIP_CHANNEL, HENDRIX_CHANNEL, NYMS_KEY from utils.log_helper import setup_logger from aioredis.commands import Redis from aiohttp import WSCloseCode import pytest import asyncio logger = setup_logger(__name__) logger_state = setup_logger(__name__ + HXApplicationState.__name__) redis_spec = dir(Redis) redis_spec.remove('__await__') # redis_mock_conf = AsyncMock(return_value=Mock(name='redis_mock', # spec=redis_spec)) # with patch('aioredis.create_redis', redis_mock_conf) as aiored: @pytest.fixture def app(): return HXApplication() @pytest.fixture def appstate(): return HXApplicationState(logger_state)
from aiohttp import web, WSMsgType, WSCloseCode from utils.log_helper import setup_logger import traceback logger = setup_logger(__name__) good_exit_code = WSCloseCode.OK good_exit_message = 'graceful exit' class WebSocketView(web.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.app = self.request.app async def get(self): ws = web.WebSocketResponse() await ws.prepare(self.request) ws_id = self.app.extract_websockets_id(self.request, ws) logger.info("received connection from : %s", ws_id) await self.app.handle_ws_connect(ws_id, ws) exit_message = good_exit_message exit_code = good_exit_code async for msg_raw in ws: if msg_raw.type == WSMsgType.TEXT: try: await self.app.process_msg_outbound(msg_raw.data, ws_id) except (ValueError, Exception) as e: logger.error('[%s] generic error. Exception: %s', ws_id, e) logger.error('\n%s', traceback.format_exc())
from aiohttp.test_utils import TestClient, TestServer, loop_context import asyncio from unittest.mock import patch, ANY import time import os import sys import json import re import pytest sys.path.append(os.getcwd()) from websockets_server.core.server import HXApplication, nyms from websockets_server.core.queries import lobby_help from utils.log_helper import setup_logger logger = setup_logger(__file__.replace(os.path.sep, '_')) def log_decorate(method): async def decorated(): result = await method() instance = str(method.__self__) pat = re.compile('.*at(.*)') inst = pat.search(instance).groups()[0] logger.debug('[%s][%s] received [%s]', inst, method.__name__, result) return result return decorated def clients_context(routine, patch_nyms=nyms):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.logger = setup_logger(__name__) self.bot = telebot.TeleBot(tlgrm_secrets.token1) self.chat_id = tlgrm_secrets.chat_id
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.logger = setup_logger(__name__)