Question

First, my code.

HTML

<form action= "/" onSubmit= "return validate(this);" method= "post">
    <!--irrelevant from this point-->

Javascript, later in the file

<script language= "JavaScript">

    function validate(form){

        if(form.text_box.value == ""){
            alert("Please enter something");
            return false;
        }

        search_string = form.text_box.value;
        var encoded = encodeURIComponent(search_string).replace(/%20/g,'+');

        form.action = "/search_results/" + encoded;
        return true;
    }
</script>

Lastly, the python/flask backend.

@maverick.route('/search_results/<search>', methods= ['GET', 'POST'])
def generateSearchResults(search = None):
    search_string = urllib.unquote_plus(search)

To explain, I am trying to quote a string before I put it in my url, because that string will contain slashes. However, when I do the search, the page doesn't load and I see this is the url bar.

http://localhost:7666/search_results/%2Fthis%2Fis%2Fmy%2Fsearch

Does anyone see any problems with my setup?

Was it helpful?

Solution

/search_results/%2Fthis%2Fis%2Fmy%2Fsearch isn't opening because werkzeug router is decoding it internally before mapping it to a view and it is resulting in /search_results//this/is/my/search which is not compatible with the pattern /search_results/<search> in your endpoint, hence the 404 error.

You can encode the string twice with javascript (which would result in %252Fthis%252Fis%252Fmy%252Fsearch) and /search_results/%252Fthis%252Fis%252Fmy%252Fsearch will be mapped correctly to your view function. Note that flask will automatically decode it once so you'll need to decode the value received in search parameter once again.

The other (and cleaner) way it to pass the input string as URL query parameters like /search?q=this/is/my/search. To achieve this, modify the endpoint pattern like so:

@maverick.route('/search_results', methods= ['GET', 'POST'])
def generateSearchResults():
    search_string = request.args.get('q')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top