Home > Software engineering >  Flask: remove end of line characters from url
Flask: remove end of line characters from url

Time:01-18

i need to remove the end of line characters from incoming requests in flask. If the route is https://localhost/test\r\n I need to remove \r\n. This is due to an issue from a oher program, that is alwas sending these. So is there a way to make this neater?

@app.route("/test")
@app.route("/test\r\n")
def test():
    return "TEST"

Thanks in advance

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • Related