def handle_request(raw_request): request = jim.unpack(raw_request) action_name = request.get('action') if validate_request(request): controller = resolve(action_name) if controller: try: response = controller(request) if response.get('code') != 200: logging.error('Wrong request format') else: logging.info( f'Request is valid and processed by controller') except Exception as err: logging.critical(err) response = make_response(request, 500, 'Internal server error') else: logging.error(f'Action {action_name} does not exits') response = make_404(request) else: logging.error('Request is not valid') response = make_400(request) return jim.pack(response)
def test_pack_unpack(): request = { 'time': datetime.now().timestamp(), 'action': 'now', 'data': 'Hello' } b_request = pack(request) request = unpack(b_request) assert request.get('action') == 'now' assert request.get('data') == 'Hello'
def get_presence_msg(): time = datetime.datetime.now() msg = { "action": "now", "time": time.isoformat(), "user": { "account_name": "anonim", "status": "Yep, I am here!" }, "data": "Hello" } return jim.pack(msg)
def main(): try: sock = socket.socket() sock.bind((host, port)) sock.listen(5) logging.info(f'Server started with {host}:{port}') while True: client, address = sock.accept() logging.info(f'Client detected {address}') b_request = client.recv(settings.BUFFERSIZE) request = jim.unpack(b_request) action_name = request.get('action') if validate_request(request): controller = resolve(action_name) if controller: try: response = controller(request) if response.get('code') != 200: logging.error('Wrong request format') else: logging.info( f'Request is valid and processed by controller' ) except Exception as err: logging.critical(err) response = make_response(request, 500, 'Internal server error') else: logging.error(f'Action {action_name} does not exits') response = make_404(request) else: logging.error('Request is not valid') response = make_400(request) response = jim.pack(response) logging.info('Send response to client') client.sendall(response) except KeyboardInterrupt: logging.info('Server closed')
def get_response_msg(): msg = {"response": 200, "alert": "Необязательное сообщение/уведомление"} return jim.pack(msg)
sock.listen(5) print(f'Server started with {host}:{port}') while True: client, address = sock.accept() print(f'Client detected { address }') b_request = client.recv(settings.BUFFERSIZE) request = jim.unpack(b_request) action_name = request.get('action') if validate_request(request): controller = resolve(action_name) if controller: try: response = controller(request) except Exception as err: print(err) response = make_response(request, 500, 'Internal server error') else: print('Action { action_name } does not exits') response = make_404(request) else: print('Request is not valid') response = make_400(request) response = jim.pack(response) client.sendall(response) except KeyboardInterrupt: print('Server closed')