Flask: remove end of line characters from url

You can use middleware to solve the issue, as you can wrap your application and modify input and output before the application.

Here is a working example of such:

from flask import Flask

app = Flask(__name__)


class PathNormaliser:
    """
    Simple WSGI middleware
    """
    def __init__(self, app):
        self._app = app

    def __call__(self, environ, start_response):
        environ['PATH_INFO'] = environ['PATH_INFO'].replace("\\r", "").replace("\\n", "")
        environ['REQUEST_URI'] = environ['REQUEST_URI'].replace("\\r", "").replace("\\n", "")
        environ['RAW_URI'] = environ['RAW_URI'].replace("\\r", "").replace("\\n", "")
        return self._app(environ, start_response)


app.wsgi_app = PathNormaliser(app.wsgi_app)


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"


app.run()

You can read more about it in a thread similiar to your case here: modify flask url before routing

Or alternatively, you can read about WSGI middleware here: https://flask.palletsprojects.com/en/2.0.x/api/?highlight=middleware#flask.Flask.wsgi_app


You could implement a simple WSGI middleware that fixes the URL before they are processed by Flask. That might look something like:

from flask import Flask


class FixURLMiddleware:
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        environ["PATH_INFO"] = environ["PATH_INFO"].strip()
        return self.app(environ, start_response)


app = Flask(__name__)
app.wsgi_app = FixURLMiddleware(app.wsgi_app)


@app.route("/hello")
def hello():
    return "Hello, world"


if __name__ == "__main__":
    app.run()

For any incoming request, this will call the strip() method (which removes whitespace, including newlines and carriage returns, from the start and end of strings) on the path before the request is handled by Flask.