refactor gateway.py