update from O'Reilly repo

This commit is contained in:
Luciano Ramalho
2021-03-22 12:24:21 -03:00
parent e1cd63aa04
commit 2f8bf06270
28 changed files with 470 additions and 125 deletions

View File

@@ -0,0 +1,28 @@
domainlib demonstration
=======================
Run Python's async console (requires Python ≥ 3.8)::
$ python3 -m asyncio
I'll see ``asyncio`` imported automatically::
>>> import asyncio
Now you can experiment with ``domainlib``.
At the `>>>` prompt, type these commands::
>>> from domainlib import *
>>> await probe('python.org')
Note the result.
Next::
>>> names = 'python.org rust-lang.org golang.org n05uch1an9.org'.split()
>>> async for result in multi_probe(names):
... print(*result, sep='\t')
Note that if you run the last two lines again,
the results are likely to appear in a different order.

View File

@@ -1,30 +1,28 @@
#!/usr/bin/env python3
from curio import run, TaskGroup
from curio.socket import getaddrinfo, gaierror
import curio.socket as socket
from keyword import kwlist
MAX_KEYWORD_LEN = 4 # <1>
MAX_KEYWORD_LEN = 4
async def probe(domain: str) -> tuple[str, bool]: # <2>
async def probe(domain: str) -> tuple[str, bool]: # <1>
try:
await getaddrinfo(domain, None) # <4>
except gaierror:
await socket.getaddrinfo(domain, None) # <2>
except socket.gaierror:
return (domain, False)
return (domain, True)
async def main() -> None: # <5>
names = (kw for kw in kwlist if len(kw) <= MAX_KEYWORD_LEN) # <6>
domains = (f'{name}.dev'.lower() for name in names) # <7>
async with TaskGroup() as group:
async def main() -> None:
names = (kw for kw in kwlist if len(kw) <= MAX_KEYWORD_LEN)
domains = (f'{name}.dev'.lower() for name in names)
async with TaskGroup() as group: # <3>
for domain in domains:
await group.spawn(probe, domain)
async for task in group: # <9>
domain, found = task.result # <10>
await group.spawn(probe, domain) # <4>
async for task in group: # <5>
domain, found = task.result
mark = '+' if found else ' '
print(f'{mark} {domain}')
if __name__ == '__main__':
run(main()) # <11>
run(main()) # <6>

View File

@@ -1,5 +1,5 @@
from curio import TaskGroup
from curio.socket import getaddrinfo, gaierror
import curio.socket as socket
from collections.abc import Iterable, AsyncIterator
from typing import NamedTuple
@@ -9,10 +9,10 @@ class Result(NamedTuple):
found: bool
async def probe(domain: str) -> Result:
async def probe(domain: str) -> Result:
try:
await getaddrinfo(domain, None)
except gaierror:
await socket.getaddrinfo(domain, None)
except socket.gaierror:
return Result(domain, False)
return Result(domain, True)