Debian Codegraph @

examples/async.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/python3
2 """
3 Async/await DNS lookup using Twisted's APIs.
4 """
5 from __future__ import print_function
6
7 # The Twisted code we'll be using:
8 from twisted.names import client
9
10 from crochet import setup, wait_for
11 setup()
12
13
14 # Crochet layer, wrapping Twisted's DNS library in a blocking call.
15 # Uses async/await.
16 @wait_for(timeout=5.0)
17 async def gethostbyname(name):
18 """Lookup the IP of a given hostname.
19
20 Unlike socket.gethostbyname() which can take an arbitrary amount of time
21 to finish, this function will raise crochet.TimeoutError if more than 5
22 seconds elapse without an answer being received.
23 """
24 result = await client.lookupAddress(name)
25 return result[0][0].payload.dottedQuad()
26
27
28 if __name__ == '__main__':
29 # Application code using the public API - notice it works in a normal
30 # blocking manner, with no event loop visible:
31 import sys
32 name = sys.argv[1]
33 ip = gethostbyname(name)
34 print(name, "->", ip)