如何用连字符或下划线替换URL中具有path参数的空格

2024-05-12 19:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如果这个Q没有意义,我很抱歉,但是有没有一种方法可以在URL中(仅)使用path参数构建它时用连字符替换空格

我的设想如下:

我有一个查看方法,如下所示:

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): .....),并执行我从上面的服务导入的所有操作(for ref)

现在,当我运行时,示例URL为

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

这里我保留了在数据库中执行查询的空间(在db中它存储为martin king),但我不想在URL中显示相同的内容,而是用连字符替换它

我有其他方法来更改数据库中的所有值(删除空格,但这不是一个合适的解决方案)

预期o/p:

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

在这里,我如何保留空间,将其作为参数传递给函数,同时只在URL中替换?这可能吗

非常感谢您的帮助


Tags: to方法appurlsearch参数defwith
2条回答

如果要在保留空格的同时查询数据库,只需使用urllib.parse.unquote对其进行url卸载,并在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'

相关问题 更多 >