Last active
June 10, 2021 15:23
-
-
Save seler/ec2e06417969bcbf7fab79c393135ecb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from handlers import handlers, invalid_command, Exit | |
def get_greeting(): | |
commands = ", ".join(handlers) | |
return ( | |
f"available commands are: {commands}\n" | |
"hit CTRL+C or type exit to exit" | |
) | |
def receive_command(): | |
command, *arguments = input("$ ").split() | |
return command, arguments | |
def process_command(command, arguments, context): | |
command_function = handlers.get(command, invalid_command) | |
return command_function(*arguments, **context) | |
def send(response): | |
print(response) | |
def run_server(): | |
context = { | |
"start_time": time.time(), | |
"info": "this is some fake data just to pass as example kwarg", | |
} | |
send(get_greeting()) | |
while True: | |
command, arguments = receive_command() | |
response = process_command(command, arguments, context) | |
send(response) | |
if __name__ == "__main__": | |
try: | |
run_server() | |
except (Exit, KeyboardInterrupt): | |
print("exit") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
handlers = {} | |
class Exit(Exception): | |
pass | |
def register(name): | |
def decorate(f): | |
handlers[name] = f | |
return f | |
return decorate | |
@register("serverinfo") | |
def server_info(*args, info, **kwargs): | |
return f"this is server info: {info}" | |
@register("uptime") | |
def uptime(*args, start_time, **kwargs): | |
duration = time.time() - start_time | |
return f"this is uptime: {duration}" | |
@register("newaccount") | |
def create_new_account(username, password, **kwargs): | |
return f"new account registered: {username}" | |
@register("exit") | |
def exit(*_, **__): | |
raise Exit() | |
def invalid_command(*args, **kwargs): | |
return "invalid command" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment