Skip to content

Commit

Permalink
add method run_middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
nggit committed Jan 11, 2025
1 parent 325b360 commit bacde99
Showing 1 changed file with 19 additions and 21 deletions.
40 changes: 19 additions & 21 deletions tremolo/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ def connection_lost(self, exc):

self._server['response'] = None

async def run_middlewares(self, name, reverse=False, start=0, step=1):
if reverse:
start = len(self._middlewares[name]) - 1
step = -1

while 0 <= start < len(self._middlewares[name]):
if await self._handle_middleware(
self._middlewares[name][start][1],
self._middlewares[name][start][2]):
return True

start += step

async def _handle_middleware(self, func, kwargs):
options = self.request.context.options
options.update(kwargs)
Expand Down Expand Up @@ -175,15 +188,8 @@ async def _handle_response(self, func, kwargs):
else:
self.response.set_header(b'Connection', b'close')

i = len(self._middlewares['response'])

while i > 0:
i -= 1

if await self._handle_middleware(
self._middlewares['response'][i][1],
self._middlewares['response'][i][2]):
return
if await self.run_middlewares('response', reverse=True):
return

if self.request.method == b'HEAD' or no_content:
await self.response.write(None)
Expand Down Expand Up @@ -237,15 +243,8 @@ async def _handle_response(self, func, kwargs):
b'Connection', KEEPALIVE_OR_CLOSE[self.request.http_keepalive]
)

i = len(self._middlewares['response'])

while i > 0:
i -= 1

if await self._handle_middleware(
self._middlewares['response'][i][1],
self._middlewares['response'][i][2]):
return
if await self.run_middlewares('response', reverse=True):
return

if self.request.method == b'HEAD' or no_content:
await self.response.write(None)
Expand All @@ -269,9 +268,8 @@ async def headers_received(self, response):
if self._middlewares['connect']:
await self.context.ON_CONNECT

for middleware in self._middlewares['request']:
if await self._handle_middleware(middleware[1], middleware[2]):
return
if await self.run_middlewares('request'):
return

if not self.request.is_valid:
# bad request
Expand Down

0 comments on commit bacde99

Please sign in to comment.