Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add add_middleware helper #34

Merged
merged 3 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example_uvloop.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ async def app(scope, receive, send):
})

if __name__ == '__main__':
tremolo.run(app, host='0.0.0.0', port=8000, debug=True)
tremolo.run(app, host='0.0.0.0', port=8000, debug=True, reload=True)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

setup(
name='tremolo',
version='0.0.302',
version='0.0.303',
license='MIT',
author='nggit',
author_email='[email protected]',
Expand Down
4 changes: 4 additions & 0 deletions tests/test_tremolo_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ def test_middleware(self):
self.assertEqual(func(), b'Halt!')
self.assertEqual(options, {})

def test_invalidmiddleware(self):
with self.assertRaises(ValueError):
app.add_middleware(middlewares.on_request, 'invalid')

@function
async def test_handler(self):
for handler in app.routes[1]:
Expand Down
2 changes: 1 addition & 1 deletion tremolo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = '0.0.302'
__version__ = '0.0.303'

from .tremolo import Tremolo # noqa: E402
from . import exceptions # noqa: E402,F401
Expand Down
16 changes: 13 additions & 3 deletions tremolo/tremolo.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
def wrapper(**kwargs):
return func(**kwargs)

self.add_route(path, wrapper, self.getoptions(func))
self.add_route(wrapper, path, self.getoptions(func))
return wrapper

return decorator
Expand Down Expand Up @@ -134,7 +134,7 @@
def wrapper(**kwargs):
return func(**kwargs)

self.middlewares[name].append((wrapper, self.getoptions(func)))
self.add_middleware(wrapper, name, self.getoptions(func))
return wrapper

return decorator
Expand Down Expand Up @@ -176,7 +176,17 @@

return options

def add_route(self, path, func, kwargs={}):
def add_middleware(self, func, name='request', kwargs={}):
if name not in self.middlewares:
raise ValueError('%s is not one of the: %s' %
(name, ', '.join(self.middlewares)))

self.middlewares[name].append((func, kwargs or self.getoptions(func)))

def add_route(self, func, path='/', kwargs={}):
if not kwargs:
kwargs = self.getoptions(func)

if path.startswith('^') or path.endswith('$'):
pattern = path.encode('latin-1')
self.routes[-1].append((pattern, func, kwargs))
Expand Down Expand Up @@ -281,7 +291,7 @@
module_name = os.path.splitext(base_name)[0]

if options['app_dir'] == '':
options['app_dir'] = os.getcwd()

Check warning on line 294 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L294

Added line #L294 was not covered by tests

sys.path.insert(0, options['app_dir'])

Expand Down Expand Up @@ -397,10 +407,10 @@
break
else:
if not os.path.exists(module.__file__):
if module in modules:
del modules[module]

Check warning on line 411 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L410-L411

Added lines #L410 - L411 were not covered by tests

continue

Check warning on line 413 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L413

Added line #L413 was not covered by tests

_sign = file_signature(module.__file__)

Expand Down Expand Up @@ -444,17 +454,17 @@
context=context,
loop=self._loop,
logger=self._logger)):
break

Check warning on line 457 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L457

Added line #L457 was not covered by tests
else:
lifespan.shutdown()
exc = await lifespan.exception()

if exc:
self._logger.error(exc)

Check warning on line 463 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L462-L463

Added lines #L462 - L463 were not covered by tests

async def _stop(self, task):
await task
self._loop.stop()

Check warning on line 467 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L466-L467

Added lines #L466 - L467 were not covered by tests

def _worker(self, host, port, **kwargs):
self._logger = logging.getLogger(mp.current_process().name)
Expand All @@ -477,16 +487,16 @@
try:
self._loop.run_until_complete(task)
except KeyboardInterrupt:
self._logger.info('Shutting down')
self._loop.create_task(self._stop(task))
self._loop.run_forever()

Check warning on line 492 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L490-L492

Added lines #L490 - L492 were not covered by tests
finally:
try:
exc = task.exception()

# to avoid None, SystemExit, etc. for being printed
if isinstance(exc, Exception):
self._logger.error(exc)

Check warning on line 499 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L499

Added line #L499 was not covered by tests
finally:
self._loop.close()

Expand Down Expand Up @@ -545,7 +555,7 @@
if sock.family.name == 'AF_UNIX':
os.unlink(sock.getsockname())
except FileNotFoundError:
pass

Check warning on line 558 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L558

Added line #L558 was not covered by tests
except OSError:
sock.close()

Expand Down Expand Up @@ -575,7 +585,7 @@
if getattr(__main__, attr_name) == kwargs['app']:
break
else:
attr_name = 'app'

Check warning on line 588 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L588

Added line #L588 was not covered by tests

kwargs['app'] = '%s:%s' % (__main__.__file__, attr_name)

Expand Down Expand Up @@ -616,7 +626,7 @@
self.listen(port, host=host, **kwargs)

if worker_num < 1:
raise ValueError('worker_num must be greater than 0')

Check warning on line 629 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L629

Added line #L629 was not covered by tests

try:
worker_num = min(worker_num, len(os.sched_getaffinity(0)))
Expand Down Expand Up @@ -712,12 +722,12 @@
if isinstance(attr, self.__class__):
self.__dict__.update(attr.__dict__)
else:
print('A worker process died. Restarting...')

Check warning on line 725 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L725

Added line #L725 was not covered by tests

if p.exitcode != 0 or hasattr(socks[args], 'share'):
# renew socket
# this is a workaround, especially on Windows
socks[args] = self.create_sock(

Check warning on line 730 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L730

Added line #L730 was not covered by tests
*args, options['reuse_port']
)

Expand All @@ -738,7 +748,7 @@
child_pid = parent_conn.recv()

if hasattr(socks[args], 'share'):
parent_conn.send(socks[args].share(child_pid))

Check warning on line 751 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L751

Added line #L751 was not covered by tests
else:
parent_conn.send(socks[args].fileno())

Expand All @@ -752,8 +762,8 @@

parent_conn.recv()
parent_conn.send(len(processes))
except BrokenPipeError:
break

Check warning on line 766 in tremolo/tremolo.py

View check run for this annotation

Codecov / codecov/patch

tremolo/tremolo.py#L765-L766

Added lines #L765 - L766 were not covered by tests

time.sleep(1)
except KeyboardInterrupt:
Expand Down
4 changes: 2 additions & 2 deletions websocket_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,5 @@ async def ws_handler(websocket=None, request=None, stream=False, **_):
"""

if __name__ == '__main__':
# don't forget to disable debug on production!
app.run('0.0.0.0', 8000, debug=True)
# don't forget to disable debug and reload on production!
app.run('0.0.0.0', 8000, debug=True, reload=True)
Loading