Search code examples
pythonhttp-redirectbottle

Python Bottle - Difference between "redirect" and "return template"


I have two questions regarding Bottle:

1) What is the difference between:

redirect('/login') and return template('login')

Wouldn't both make the user go on same the /login page?

2) Can I pass arguments to redirect as I do in case of return?

For e.g.:

Does this work: redirect('/login', userName="foo") as we do in this case:

return template('login', userName="foo")


Solution

  • 1) What is the difference between:

    redirect('/login') and return template('login')

    From the bottle documentation for redirect:

    To redirect a client to a different URL, you can send a 303 See Other response with the Location header set to the new URL. redirect() does that for you

    The redirect() method will send a 303 response to the user, who will then send another request to your server for the '/login' page. If you use the template() method, you will be returning the web page directly to the user.

    2) Can I pass arguments to redirect as I do in case of return?

    redirect() does not accept query variables, such as those you pass to template(). If you want to use those variables, you will need to set them explicitly on the url. E.g. to use a url '/login' with userName="foo", you need to call redirect('/login?userName="foo")

    Edit if you don't want to store all of the variables in the url, you should try to get those values when the page is rendered. e.g. Call redirect('/login') without the variables and make it the responsibility of the method that renders '/login' to call template() with the correct variables.