如果这个 Q 没有意义,我很抱歉,但是有没有办法在 URL(only( 中使用路径参数来构建它后用连字符替换空格?
我的场景是:
我有一个视图方法如下:
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'])
- 这里
search_url
我正在从模板传递
我有一个search
函数,它将search_url
作为参数(def search(search_url): .....
(并执行我从上面的服务导入的所有操作(对于ref(。
现在当我运行时,我有示例 URL,
....myapp/hi-martin%20king
在这里,我保留了在数据库中执行查询的空间(在数据库中它存储为martin king
(,但我不想在URL中显示相同的内容,而是将其替换为连字符
我有其他方法可以更改数据库中的所有值(删除空格,但这不是 tmk 合适的解决方案(
预期 O/P:
....myapp/hi-martin-king (or with an underscore) ....myapp/hi-martin_king
在这里,我如何保留空格以将其作为参数传递给函数,同时我只想在 URL 中替换?这可能吗?
任何帮助不胜感激....蒂亚
如果您想在保留空格的同时查询数据库,您可以使用urllib.parse.unquote
为查询取消转义它们,并保留它们在 url 中转义,如下所示:
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'])
如果需要原始版本,则带有%
的字符串需要取消引号。
from werkzeug import url_unquote
url_unquote('hi-martin%20king') # => 'hi-martin king'
现在您有了不带引号的字符串,您可以用连字符或下划线替换空格。
replace_character = '-'
def fix_string(s):
return s.replace(' ', replace_character)
fix_string('hi-martin king') # => 'hi-martin-king'