# Buggy code
def application(request):
    response = None

    try:
        rollback = True

        init_request(request)

        frappe.recorder.record()
        frappe.monitor.start()
        frappe.rate_limiter.apply()

        if frappe.local.form_dict.cmd:
            response = frappe.handler.handle()

        elif frappe.request.path.startswith("/api/"):
            response = frappe.api.handle()

        elif frappe.request.path.startswith("/backups"):
            response = frappe.utils.response.download_backup(request.path)

        elif frappe.request.path.startswith("/private/files/"):
            response = frappe.utils.response.download_private_file(request.path)

        elif frappe.local.request.method in ("GET", "HEAD", "POST"):
            response = frappe.website.render.render()

        else:
            raise NotFound

    except HTTPException as e:
        return e

    except frappe.SessionStopped as e:
        response = frappe.utils.response.handle_session_stopped()

    except Exception as e:
        response = handle_exception(e)

    else:
        rollback = after_request(rollback)

    finally:
        if frappe.local.request.method in ("POST", "PUT") and frappe.db and rollback:
            frappe.db.rollback()

        # set cookies
        if response and hasattr(frappe.local, "cookie_manager"):
            frappe.local.cookie_manager.flush_cookies(response=response)

        frappe.rate_limiter.update()
        frappe.monitor.stop(response)
        frappe.recorder.dump()

        _site = get_site_name(request.host)
        frappe.logger("frappe.web", allow_site=_site).info(
            {
                "site": _site,
                "remote_addr": getattr(request, "remote_addr", "NOTFOUND"),
                "base_url": getattr(request, "base_url", "NOTFOUND"),
                "full_path": getattr(request, "full_path", "NOTFOUND"),
                "method": getattr(request, "method", "NOTFOUND"),
                "scheme": getattr(request, "scheme", "NOTFOUND"),
                "http_status_code": getattr(response, "status_code", "NOTFOUND"),
            }
        )

        if response and hasattr(frappe.local, "rate_limiter"):
            response.headers.extend(frappe.local.rate_limiter.headers())

        frappe.destroy()

    return response


# Traceback (FileNotFoundError)
127.0.0.1 - - [03/Aug/2020 10:17:14] "GET / HTTP/1.0" 500 -
10:17:14 web.1            | INFO:werkzeug:127.0.0.1 - - [03/Aug/2020 10:17:14] "GET / HTTP/1.0" 500 -
10:17:14 web.1            | Traceback (most recent call last):
10:17:14 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/middlewares.py", line 16, in __call__
10:17:14 web.1            |     return super(StaticDataMiddleware, self).__call__(environ, start_response)
10:17:14 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/werkzeug/middleware/shared_data.py", line 220, in __call__
10:17:14 web.1            |     return self.app(environ, start_response)
10:17:14 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/werkzeug/middleware/shared_data.py", line 220, in __call__
10:17:14 web.1            |     return self.app(environ, start_response)
10:17:14 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/werkzeug/local.py", line 231, in application
10:17:14 web.1            |     return ClosingIterator(app(environ, start_response), self.cleanup)
10:17:14 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/werkzeug/wrappers/base_request.py", line 237, in application
10:17:14 web.1            |     resp = f(*args[:-2] + (request,))
10:17:14 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/app.py", line 103, in application
10:17:14 web.1            |     frappe.logger("frappe.web", allow_site=_site).info({
10:17:14 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/__init__.py", line 1565, in logger
10:17:14 web.1            |     return get_logger(module=module, with_more_info=with_more_info, allow_site=allow_site, filter=filter, max_size=max_size, file_count=file_count)
10:17:14 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/utils/logger.py", line 66, in get_logger
10:17:14 web.1            |     site_handler = RotatingFileHandler(sitelog_filename, maxBytes=max_size, backupCount=file_count)
10:17:14 web.1            |   File "/usr/lib/python3.6/logging/handlers.py", line 150, in __init__
10:17:14 web.1            |     BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
10:17:14 web.1            |   File "/usr/lib/python3.6/logging/handlers.py", line 57, in __init__
10:17:14 web.1            |     logging.FileHandler.__init__(self, filename, mode, encoding, delay)
10:17:14 web.1            |   File "/usr/lib/python3.6/logging/__init__.py", line 1032, in __init__
10:17:14 web.1            |     StreamHandler.__init__(self, self._open())
10:17:14 web.1            |   File "/usr/lib/python3.6/logging/__init__.py", line 1061, in _open
10:17:14 web.1            |     return open(self.baseFilename, self.mode, encoding=self.encoding)
10:17:14 web.1            | FileNotFoundError: [Errno 2] No such file or directory: '/home/frappe/frappe-bench/sites/167.71.179.108/logs/frappe.web.log'
10:17:15 web.1            | 127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=style.css HTTP/1.0" 200 -
10:17:15 web.1            | INFO:werkzeug:127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=style.css HTTP/1.0" 200 -
10:17:15 web.1            | 127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js HTTP/1.0" 200 -
10:17:15 web.1            | INFO:werkzeug:127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js HTTP/1.0" 200 -
10:17:15 web.1            | 127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js HTTP/1.0" 200 -
10:17:15 web.1            | INFO:werkzeug:127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js HTTP/1.0" 200 -
10:17:15 web.1            | 127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=console.png HTTP/1.0" 200 -
10:17:15 web.1            | INFO:werkzeug:127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=console.png HTTP/1.0" 200 -
10:17:15 web.1            | 127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=ubuntu.ttf HTTP/1.0" 200 -
10:17:15 web.1            | INFO:werkzeug:127.0.0.1 - - [03/Aug/2020 10:17:15] "GET /?__debugger__=yes&amp;cmd=resource&amp;f=ubuntu.ttf HTTP/1.0" 200 -

# Fixed code
def application(request):
    response = None

    try:
        rollback = True

        init_request(request)

        frappe.recorder.record()
        frappe.monitor.start()
        frappe.rate_limiter.apply()

        if frappe.local.form_dict.cmd:
            response = frappe.handler.handle()

        elif frappe.request.path.startswith("/api/"):
            response = frappe.api.handle()

        elif frappe.request.path.startswith("/backups"):
            response = frappe.utils.response.download_backup(request.path)

        elif frappe.request.path.startswith("/private/files/"):
            response = frappe.utils.response.download_private_file(request.path)

        elif frappe.local.request.method in ("GET", "HEAD", "POST"):
            response = frappe.website.render.render()

        else:
            raise NotFound

    except HTTPException as e:
        return e

    except frappe.SessionStopped as e:
        response = frappe.utils.response.handle_session_stopped()

    except Exception as e:
        response = handle_exception(e)

    else:
        rollback = after_request(rollback)

    finally:
        if frappe.local.request.method in ("POST", "PUT") and frappe.db and rollback:
            frappe.db.rollback()

        # set cookies
        if response and hasattr(frappe.local, "cookie_manager"):
            frappe.local.cookie_manager.flush_cookies(response=response)

        frappe.rate_limiter.update()
        frappe.monitor.stop(response)
        frappe.recorder.dump()

        frappe.logger("frappe.web", allow_site=frappe.local.site).info(
            {
                "site": get_site_name(request.host),
                "remote_addr": getattr(request, "remote_addr", "NOTFOUND"),
                "base_url": getattr(request, "base_url", "NOTFOUND"),
                "full_path": getattr(request, "full_path", "NOTFOUND"),
                "method": getattr(request, "method", "NOTFOUND"),
                "scheme": getattr(request, "scheme", "NOTFOUND"),
                "http_status_code": getattr(response, "status_code", "NOTFOUND"),
            }
        )

        if response and hasattr(frappe.local, "rate_limiter"):
            response.headers.extend(frappe.local.rate_limiter.headers())

        frappe.destroy()

    return response