Debian Codegraph @

docs/core/examples/stdiodemo.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) Twisted Matrix Laboratories.
4 # See LICENSE for details.
5
6 """
7 Example using stdio, Deferreds, LineReceiver and twisted.web.client.
8
9 Note that the WebCheckerCommandProtocol protocol could easily be used in e.g.
10 a telnet server instead; see the comments for details.
11
12 Based on an example by Abe Fettig.
13 """
14
15 from twisted.internet import reactor, stdio
16 from twisted.protocols import basic
17 from twisted.web import client
18
19
20 class WebCheckerCommandProtocol(basic.LineReceiver):
21 delimiter = b"\n" # unix terminal style newlines. remove this line
22 # for use with Telnet
23
24 def connectionMade(self):
25 self.sendLine(b"Web checker console. Type 'help' for help.")
26
27 def lineReceived(self, line):
28 # Ignore blank lines
29 if not line:
30 return
31 line = line.decode("ascii")
32
33 # Parse the command
34 commandParts = line.split()
35 command = commandParts[0].lower()
36 args = commandParts[1:]
37
38 # Dispatch the command to the appropriate method. Note that all you
39 # need to do to implement a new command is add another do_* method.
40 try:
41 method = getattr(self, "do_" + command)
42 except AttributeError:
43 self.sendLine(b"Error: no such command.")
44 else:
45 try:
46 method(*args)
47 except Exception as e:
48 self.sendLine(b"Error: " + str(e).encode("ascii"))
49
50 def do_help(self, command=None):
51 """help [command]: List commands, or show help on the given command"""
52 if command:
53 doc = getattr(self, "do_" + command).__doc__
54 self.sendLine(doc.encode("ascii"))
55 else:
56 commands = [
57 cmd[3:].encode("ascii") for cmd in dir(self) if cmd.startswith("do_")
58 ]
59 self.sendLine(b"Valid commands: " + b" ".join(commands))
60
61 def do_quit(self):
62 """quit: Quit this session"""
63 self.sendLine(b"Goodbye.")
64 self.transport.loseConnection()
65
66 def do_check(self, url):
67 """check <url>: Attempt to download the given web page"""
68 url = url.encode("ascii")
69 client.Agent(reactor).request(b"GET", url).addCallback(
70 client.readBody
71 ).addCallback(self.__checkSuccess).addErrback(self.__checkFailure)
72
73 def __checkSuccess(self, pageData):
74 msg = f"Success: got {len(pageData)} bytes."
75 self.sendLine(msg.encode("ascii"))
76
77 def __checkFailure(self, failure):
78 msg = "Failure: " + failure.getErrorMessage()
79 self.sendLine(msg.encode("ascii"))
80
81 def connectionLost(self, reason):
82 # stop the reactor, only because this is meant to be run in Stdio.
83 reactor.stop()
84
85
86 if __name__ == "__main__":
87 stdio.StandardIO(WebCheckerCommandProtocol())
88 reactor.run()