@middleware<EOL>async def normalize_postcode_middleware(request, handler):
postcode: Optional[str] = request.match_info.get('<STR_LIT>', None)<EOL>if postcode is None or postcode == "<STR_LIT>":<EOL><INDENT>return await handler(request)<EOL><DEDENT>elif not is_uk_postcode(postcode):<EOL><INDENT>raise web.HTTPNotFound(text="<STR_LIT>")<EOL><DEDENT>postcode_processed = postcode.upper().replace("<STR_LIT:U+0020>", "<STR_LIT>")<EOL>if postcode_processed == postcode:<EOL><INDENT>return await handler(request)<EOL><DEDENT>else:<EOL><INDENT>url_name = request.match_info.route.name<EOL>url = request.app.router[url_name]<EOL>params = dict(request.match_info)<EOL>params['<STR_LIT>'] = postcode_processed<EOL>raise web.HTTPMovedPermanently(str(url.url_for(**params)))<EOL><DEDENT>
If there is a postcode in the url it validates and normalizes it.