MCPcopy Create free account
hub / github.com/bslatkin/effectivepython / ServerSession

Class ServerSession

example_code/item_076.py:83–142  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

81 pass
82
83class ServerSession(Connection):
84 def __init__(self, *args):
85 super().__init__(*args)
86 self.clear_state()
87
88
89 print("Example 3")
90 def loop(self):
91 while command := self.receive():
92 match command.split(" "):
93 case "PARAMS", lower, upper:
94 self.set_params(lower, upper)
95 case ["NUMBER"]:
96 self.send_number()
97 case "REPORT", decision:
98 self.receive_report(decision)
99 case ["CLEAR"]:
100 self.clear_state()
101 case _:
102 raise UnknownCommandError(command)
103
104
105 print("Example 4")
106 def set_params(self, lower, upper):
107 self.clear_state()
108 self.lower = int(lower)
109 self.upper = int(upper)
110
111
112 print("Example 5")
113 def next_guess(self):
114 if self.secret is not None:
115 return self.secret
116
117 while True:
118 guess = random.randint(self.lower, self.upper)
119 if guess not in self.guesses:
120 return guess
121
122 def send_number(self):
123 guess = self.next_guess()
124 self.guesses.append(guess)
125 self.send(format(guess))
126
127
128 print("Example 6")
129 def receive_report(self, decision):
130 last = self.guesses[-1]
131 if decision == CORRECT:
132 self.secret = last
133
134 print(f"Server: {last} is {decision}")
135
136
137 print("Example 7")
138 def clear_state(self):
139 self.lower = None
140 self.upper = None

Callers 1

handle_connectionFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected