Skip to content

Commit

Permalink
Adopted Black for code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Mar 29, 2022
1 parent 65b07ba commit 1c9b467
Show file tree
Hide file tree
Showing 25 changed files with 1,073 additions and 678 deletions.
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ repos:
rev: v2.31.1
hooks:
- id: pyupgrade
args: [ "--py37-plus", "--keep-runtime-typing" ]
args: [ "--py37-plus" ]

- repo: https://github.com/pre-commit/mirrors-autopep8
rev: v1.6.0
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: autopep8
- id: black

- repo: https://github.com/pycqa/isort
rev: 5.10.1
Expand Down
36 changes: 18 additions & 18 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,32 @@
from packaging.version import parse

extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx_autodoc_typehints',
'sphinxcontrib.asyncio'
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx_autodoc_typehints",
"sphinxcontrib.asyncio",
]

templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'The Asphalt Framework (core)'
author = 'Alex Grönholm'
copyright = '2015, ' + author
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
project = "The Asphalt Framework (core)"
author = "Alex Grönholm"
copyright = "2015, " + author

v = parse(version('asphalt'))
v = parse(version("asphalt"))
version = v.base_version
release = v.public

language = None

exclude_patterns = ['_build']
pygments_style = 'sphinx'
highlight_language = 'python3'
exclude_patterns = ["_build"]
pygments_style = "sphinx"
highlight_language = "python3"
todo_include_todos = False

html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
htmlhelp_basename = 'asphaltdoc'
html_theme = "sphinx_rtd_theme"
html_static_path = ["_static"]
htmlhelp_basename = "asphaltdoc"

intersphinx_mapping = {'python': ('http://docs.python.org/3/', None)}
intersphinx_mapping = {"python": ("http://docs.python.org/3/", None)}
74 changes: 37 additions & 37 deletions docs/tutorials/webnotifier.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,12 @@ adapt code from the `aiohttp HTTP client tutorial`_::
async def run(self, ctx):
async with aiohttp.ClientSession() as session:
while True:
async with session.get('http://imgur.com') as resp:
async with session.get("http://imgur.com") as resp:
await resp.text()

await asyncio.sleep(10)

if __name__ == '__main__':
if __name__ == "__main__":
run_application(ApplicationComponent(), logging=logging.DEBUG)

Great, so now the code fetches the contents of ``http://imgur.com`` at 10 second intervals.
Expand All @@ -70,13 +70,13 @@ So, modify the code as follows::
last_modified = None
async with aiohttp.ClientSession() as session:
while True:
headers = {'if-modified-since': last_modified} if last_modified else {}
async with session.get('http://imgur.com', headers=headers) as resp:
logger.debug('Response status: %d', resp.status)
headers = {"if-modified-since": last_modified} if last_modified else {}
async with session.get("http://imgur.com", headers=headers) as resp:
logger.debug("Response status: %d", resp.status)
if resp.status == 200:
last_modified = resp.headers['date']
last_modified = resp.headers["date"]
await resp.text()
logger.info('Contents changed')
logger.info("Contents changed")

await asyncio.sleep(10)

Expand All @@ -103,24 +103,24 @@ to the logger::
async with aiohttp.ClientSession() as session:
last_modified, old_lines = None, None
while True:
logger.debug('Fetching webpage')
headers = {'if-modified-since': last_modified} if last_modified else {}
async with session.get('http://imgur.com', headers=headers) as resp:
logger.debug('Response status: %d', resp.status)
logger.debug("Fetching webpage")
headers = {"if-modified-since": last_modified} if last_modified else {}
async with session.get("http://imgur.com", headers=headers) as resp:
logger.debug("Response status: %d", resp.status)
if resp.status == 200:
last_modified = resp.headers['date']
new_lines = (await resp.text()).split('\n')
last_modified = resp.headers["date"]
new_lines = (await resp.text()).split("\n")
if old_lines is not None and old_lines != new_lines:
difference = unified_diff(old_lines, new_lines)
logger.info('Contents changed:\n%s', difference)
logger.info("Contents changed:\n%s", difference)

old_lines = new_lines

await asyncio.sleep(10)

This modified code now stores the old and new contents in different variables to enable them to be
compared. The ``.split('\n')`` is needed because :func:`~difflib.unified_diff` requires the input
to be iterables of strings. Likewise, the ``'\n'.join(...)`` is necessary because the output is
compared. The ``.split("\n")`` is needed because :func:`~difflib.unified_diff` requires the input
to be iterables of strings. Likewise, the ``"\n".join(...)`` is necessary because the output is
also an iterable of strings.

Sending changes via email
Expand All @@ -145,28 +145,28 @@ And to make the the results look nicer in an email message, you can switch to us
class ApplicationComponent(CLIApplicationComponent):
async def start(self, ctx):
self.add_component(
'mailer', backend='smtp', host='your.smtp.server.here',
message_defaults={'sender': 'your@email.here', 'to': 'your@email.here'})
"mailer", backend="smtp", host="your.smtp.server.here",
message_defaults={"sender": "your@email.here", "to": "your@email.here"})
await super().start(ctx)

async def run(self, ctx):
async with aiohttp.ClientSession() as session:
last_modified, old_lines = None, None
diff = HtmlDiff()
while True:
logger.debug('Fetching webpage')
headers = {'if-modified-since': last_modified} if last_modified else {}
async with session.get('http://imgur.com', headers=headers) as resp:
logger.debug('Response status: %d', resp.status)
logger.debug("Fetching webpage")
headers = {"if-modified-since": last_modified} if last_modified else {}
async with session.get("http://imgur.com", headers=headers) as resp:
logger.debug("Response status: %d", resp.status)
if resp.status == 200:
last_modified = resp.headers['date']
new_lines = (await resp.text()).split('\n')
last_modified = resp.headers["date"]
new_lines = (await resp.text()).split("\n")
if old_lines is not None and old_lines != new_lines:
difference = diff.make_file(old_lines, new_lines, context=True)
await ctx.mailer.create_and_deliver(
subject='Change detected in %s' % event.source.url,
subject="Change detected in %s" % event.source.url,
html_body=difference)
logger.info('Sent notification email')
logger.info("Sent notification email")

old_lines = new_lines

Expand Down Expand Up @@ -226,13 +226,13 @@ Next, add another class in the same module that will do the HTTP requests and ch
async with aiohttp.ClientSession() as session:
last_modified, old_lines = None, None
while True:
logger.debug('Fetching contents of %s', self.url)
headers = {'if-modified-since': last_modified} if last_modified else {}
logger.debug("Fetching contents of %s", self.url)
headers = {"if-modified-since": last_modified} if last_modified else {}
async with session.get(self.url, headers=headers) as resp:
logger.debug('Response status: %d', resp.status)
logger.debug("Response status: %d", resp.status)
if resp.status == 200:
last_modified = resp.headers['date']
new_lines = (await resp.text()).split('\n')
last_modified = resp.headers["date"]
new_lines = (await resp.text()).split("\n")
if old_lines is not None and old_lines != new_lines:
self.changed.dispatch(old_lines, new_lines)

Expand Down Expand Up @@ -266,7 +266,7 @@ Asphalt application::
# This part is run when the context is being torn down
task.cancel()
await asyncio.gather(task, return_exceptions=True)
logging.info('Shut down web page change detector')
logging.info("Shut down web page change detector")

The component's ``start()`` method starts the detector's ``run()`` method as a new task, adds
the detector object as resource and installs an event listener that will shut down the detector
Expand All @@ -280,10 +280,10 @@ become somewhat lighter::

class ApplicationComponent(CLIApplicationComponent):
async def start(self, ctx):
self.add_component('detector', ChangeDetectorComponent, url='http://imgur.com')
self.add_component("detector", ChangeDetectorComponent, url="http://imgur.com")
self.add_component(
'mailer', backend='smtp', host='your.smtp.server.here',
message_defaults={'sender': 'your@email.here', 'to': 'your@email.here'})
"mailer", backend="smtp", host="your.smtp.server.here",
message_defaults={"sender": "your@email.here", "to": "your@email.here"})
await super().start(ctx)

async def run(self, ctx):
Expand All @@ -292,8 +292,8 @@ become somewhat lighter::
async for event in stream:
difference = diff.make_file(event.old_lines, event.new_lines, context=True)
await ctx.mailer.create_and_deliver(
subject='Change detected in %s' % event.source.url, html_body=difference)
logger.info('Sent notification email')
subject="Change detected in %s" % event.source.url, html_body=difference)
logger.info("Sent notification email")

The main application component will now use the detector resource added by
``ChangeDetectorComponent``. It adds one event listener which reacts to change events by creating
Expand Down
8 changes: 4 additions & 4 deletions examples/tutorial1/echo/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ def __init__(self, message: str):
self.message = message

async def run(self, ctx):
reader, writer = await open_connection('localhost', 64100)
writer.write(self.message.encode() + b'\n')
reader, writer = await open_connection("localhost", 64100)
writer.write(self.message.encode() + b"\n")
response = await reader.readline()
writer.close()
print('Server responded:', response.decode().rstrip())
print("Server responded:", response.decode().rstrip())


if __name__ == '__main__':
if __name__ == "__main__":
component = ClientComponent(sys.argv[1])
run_application(component)
6 changes: 3 additions & 3 deletions examples/tutorial1/echo/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ async def client_connected(reader, writer):
message = await reader.readline()
writer.write(message)
writer.close()
print('Message from client:', message.decode().rstrip())
print("Message from client:", message.decode().rstrip())


class ServerComponent(Component):
async def start(self, ctx):
await start_server(client_connected, 'localhost', 64100)
await start_server(client_connected, "localhost", 64100)


if __name__ == '__main__':
if __name__ == "__main__":
component = ServerComponent()
run_application(component)
4 changes: 2 additions & 2 deletions examples/tutorial1/tests/test_client_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ def server_component(event_loop, context):


def test_client(event_loop, server_component, context, capsys):
client = ClientComponent('Hello!')
client = ClientComponent("Hello!")
event_loop.run_until_complete(client.start(context))
exc = pytest.raises(SystemExit, event_loop.run_forever)
assert exc.value.code == 0

# Grab the captured output of sys.stdout and sys.stderr from the capsys fixture
out, err = capsys.readouterr()
assert out == 'Message from client: Hello!\nServer responded: Hello!\n'
assert out == "Message from client: Hello!\nServer responded: Hello!\n"
14 changes: 9 additions & 5 deletions examples/tutorial2/webnotifier/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@

class ApplicationComponent(CLIApplicationComponent):
async def start(self, ctx):
self.add_component('detector', ChangeDetectorComponent)
self.add_component('mailer', backend='smtp')
self.add_component("detector", ChangeDetectorComponent)
self.add_component("mailer", backend="smtp")
await super().start(ctx)

async def run(self, ctx):
diff = HtmlDiff()
async with aclosing(ctx.detector.changed.stream_events()) as stream:
async for event in stream:
difference = diff.make_file(event.old_lines, event.new_lines, context=True)
difference = diff.make_file(
event.old_lines, event.new_lines, context=True
)
await ctx.mailer.create_and_deliver(
subject='Change detected in %s' % event.source.url, html_body=difference)
logger.info('Sent notification email')
subject=f"Change detected in {event.source.url}",
html_body=difference,
)
logger.info("Sent notification email")
21 changes: 12 additions & 9 deletions examples/tutorial2/webnotifier/detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ async def run(self):
async with aiohttp.ClientSession() as session:
last_modified, old_lines = None, None
while True:
logger.debug('Fetching contents of %s', self.url)
headers = {'if-modified-since': last_modified} if last_modified else {}
logger.debug("Fetching contents of %s", self.url)
headers = {"if-modified-since": last_modified} if last_modified else {}
async with session.get(self.url, headers=headers) as resp:
logger.debug('Response status: %d', resp.status)
logger.debug("Response status: %d", resp.status)
if resp.status == 200:
last_modified = resp.headers['date']
new_lines = (await resp.text()).split('\n')
last_modified = resp.headers["date"]
new_lines = (await resp.text()).split("\n")
if old_lines is not None and old_lines != new_lines:
self.changed.dispatch(old_lines, new_lines)

Expand All @@ -51,14 +51,17 @@ def __init__(self, url: str, delay: int = 10):
@context_teardown
async def start(self, ctx):
detector = Detector(self.url, self.delay)
ctx.add_resource(detector, context_attr='detector')
ctx.add_resource(detector, context_attr="detector")
task = ctx.loop.create_task(detector.run())
logging.info('Started web page change detector for url "%s" with a delay of %d seconds',
self.url, self.delay)
logging.info(
'Started web page change detector for url "%s" with a delay of %d seconds',
self.url,
self.delay,
)

yield

# This part is run when the context is finished
task.cancel()
await asyncio.gather(task, return_exceptions=True)
logging.info('Shut down web page change detector')
logging.info("Shut down web page change detector")
7 changes: 1 addition & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,7 @@ local_scheme = "dirty-tag"
[tool.isort]
src_paths = ["src"]
skip_gitignore = true
line_length = 99
multi_line_output = 4
known_first_party = ["asphalt.core"]

[tool.autopep8]
max_line_length = 99
profile = "black"

[tool.flake8]
max-line-length = 99
Expand Down

0 comments on commit 1c9b467

Please sign in to comment.