如何处理多个包含斜杠的参数?

use*_*622 11 python flask

我有一个 Flask 应用程序,需要向其传递几个包含斜杠的参数。例如,我有 parameter1 = "Clothes/Bottoms"parameter2 = "Pants/Jeans"。我尝试这样做:

在我的 HTML/JS 中:

par1 = encodeURIComponent(parameter1);
par2 = encodeURIComponent(parameter2);
console.log("Par1 = ",par1," par2 = ",par2);
$.ajax({
     type:'post',
     url:'/get_data'+'/'+par1+'/'+par2,
     ....
});
Run Code Online (Sandbox Code Playgroud)

在我的app.py

 @app.route('/get_data/<path:par1>/<path:par2>/',methods=['GET','POST'])
 def get_data(par1, par2):
     print("In get_data with par1 ",par1," and par2 ",par2)
     ....
Run Code Online (Sandbox Code Playgroud)

我可以从 Javascript 打印输出中看到,这两个参数在编码后看起来都很好,但 Python 打印输出是:

 In get_data with par1 Clothes and par2 Bottoms/Pants/Jeans
Run Code Online (Sandbox Code Playgroud)

par1因此,它以某种方式将s中的斜杠误"Clothes/Bottoms"认为是 URL 的一部分,并转换"Bottoms"par2.

有没有比仅添加更好的方法来处理带有斜杠的多个参数path:

glh*_*lhr 8

对于/get_data/<path:par1>/<path:par2>/,Flask 在收到类似 的请求时无法“知道”哪个斜杠是分隔符/get_data/Clothes/Bottoms/Pants/Jeans/

如果斜杠的数量par1是固定的,您可以将路径作为单个参数接收,然后将其分成两个:

@app.route('/get_data/<path:pars>/')
def get_data(pars):
     par1 = '/'.join(pars.split("/",2)[:2]) #par1 is everything up until the 2nd slash
     par2 = pars.split("/",2)[2:][0] #par2 is everything after the second slash
Run Code Online (Sandbox Code Playgroud)

否则,您可以简单地将分隔符斜杠替换为另一个字符,例如:

@app.route('/get_data/<path:par1>-<path:par2>/')
Run Code Online (Sandbox Code Playgroud)