pythonflaskhttp-redirectlti

Flask Redirect to External URL With Parameters


I'd like to use flask to redirect the user to an external URL with parameters. I've recently came across this post about redirect and url_for which only works for internal URLs, and this post that had a similar question about external URLs with parameters, but I cannot use HTTP code 307 for the LTI product I'm working on. The solutions in the latter post also didn't include how to pass parameters.

I know that url_for accepts arguments, but I cannot use that for an external URL.

I'd like something similar to this:

return redirect(f'{redirect_url}?lti_msg={message}&lti_log={log}')

where

redirect_url = 'https://www.example.com' # external url
lti_msg = 'An example message' # parameter
lti_log = 'An example log message' # parameter

Is there a way to pass URL parameters as arguments instead of using f-strings? Thank you all in advance.


Solution

  • After some research and guidance by @Selcuk, I was able to implement it using urllib.parse.urlencode

    Import:

    from urllib.parse import urlencode
    

    Usage:

    redirect_baseUrl = 'https://www.example.com' # external url
    lti_msg = 'An example message' # parameter
    lti_log = 'An example log message' # parameter
    
    parameters = dict(lti_msg=message, lti_log=log)
    redirect_url = redirect_baseUrl + ("?" + urlencode(parameters) if parameters else "")
    return redirect(redirect_url)
    

    Note: Using the format I had used in the question would cause incomplete data passed when special characters such as & are in one of the parameters. urlencode perfectly addresses this issue