Search code examples
pythonflask

How do I make Flask redirect("abc") return relative to the URL path the application is running on?


I have my Flask application running on domain.com/test/. In my code, I'd like a redirect to return a user to domain.com/test/login if they hit any URL in the application (route handler or not) and are not logged in.

If I do redirect("/abc"), it sends them to domain.com/abc. If I do redirect("abc"), and they come from a route, such as domain.com/test/bla/ , it sends them to domain.com/test/bla/abc.

I would just like the redirect to send them to [url-flask-app-is-running-on]/[the-redirect-path-segment]

On another note, can I give redirect an endpoint instead of a string path?


Solution

  • There are two ways:

    1. you can use return redirect('domain.com/test/login') which is a full path.

    2. if your code is like:

      @app.route('/test/login')
      def login_form()
           pass # Login form
      

      then you can use return redirect(flask.url_for('login_form').

    Source of redirect

    Source of url_for