1

I am sorry if this Q makes no sense , but is there a way to replace spaces with hyphen in URL's(only) having used path parameter to build it ?

My scenario is as :

I have a view method as below:

from app.service import *

@app.route('/myapp/<search_url>',methods=['GET','POST'])
def search_func(search_url):
    print(search_url) // This prints 'hi-martin king' and i need to pass 'hi-martin king' to below with preserving space
    search_q = search(search_url) 
    return render_template('wordsearch.html',data=search_q['data'])
  • here search_url I am passing from template

I have the search function which takes search_url as argument(def search(search_url): .....) and does all operations (for ref) which i have imported from service above.

Now when I run , i have the sample URL as,

....myapp/hi-martin%20king

Here I am preserving space to perform query in database (In db it is stored as martin king), but I don't want to show the same in URL instead replace it with a hyphen

I have other way that changing all the values in database (removing spaces but this is tmk not a appropriate solution)

expected o/p:

....myapp/hi-martin-king  (or with an underscore) ....myapp/hi-martin_king 

Here how can i preserve spaces to pass it as argument to the function and at the same time I want to replace only in URL ? Is this possible ?

Any help is appreciated ....TIA

KcH
  • 3,302
  • 3
  • 21
  • 46

2 Answers2

2

If you want to query your db while preserving spaces you can just url-unescape them for the query using urllib.parse.unquote and preserve them escaped in the url as follows:

import urllib.parse

from app.service import *

@app.route('/myapp/<search_url>',methods=['GET','POST'])
def search_func(search_url):
    unquoted_search = urllib.parse.unquote(search_url)
    search_q = search(unquoted_search) 
    return render_template('wordsearch.html',data=search_q['data'])
SARA E
  • 189
  • 1
  • 6
2

The string with % in needs unquoting if you want the raw version.

from werkzeug import url_unquote

url_unquote('hi-martin%20king')  # => 'hi-martin king'

Now you have the unquoted string, you can replace spaces with either a hyphen or an underscore.

replace_character = '-'

def fix_string(s):
    return s.replace(' ', replace_character)

fix_string('hi-martin king')  # => 'hi-martin-king'
blueteeth
  • 3,330
  • 1
  • 13
  • 23