我有一个烧瓶应用程序,我需要传递包含斜杠的几个参数。例如,我有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,
....
});在我的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)
....我从Javascript打印输出中可以看出,这两个参数在编码后看起来都很好,但是Python打印出的结果是:
In get_data with par1 Clothes and par2 Bottoms/Pants/Jeans因此,它以某种方式将par1's "Clothes/Bottoms"中的斜杠错误为URL的一部分,并将"Bottoms"转换为par2。
有比仅仅添加path:更好的方法来处理多个参数吗?
发布于 2019-04-06 15:54:22
对于/get_data/<path:par1>/<path:par2>/,当它收到像/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否则,只需将分隔符斜杠替换为另一个字符,如下所示:
@app.route('/get_data/<path:par1>-<path:par2>/')发布于 2019-04-06 17:55:36
了解烧瓶的路由。暂时搁置在JavaScript中使用的编码。
path转换器使用的Regex模式是[^/].*?。这允许url路径中的任意数量的/。这意味着只有part1 get_data/<path:par1>可以同时接受get_data/Clothes/Bottoms或get_data/Clothes/Bottoms/Pants/Jeans。
您在part1和par2中使用两个part1转换器,这很糟糕,因为一个part1可以接受所有的斜杠。
现在是另一个问题了。为什么即使在编码url之后,它也不能像预期的那样工作。
烧瓶使用Werkzeug默认的WSGI服务器。而WSGI库在使用它进行路由之前没有转义uri。也就是说,当涉及到路由时,get_data/Clothes%2FBottoms被转换为get_data/Clothes/Bottoms。在您的例子中,路由器在这里接收get_data/Clothes/Bottoms/Pants/Jeans,它将“衣服”作为part1,rest作为part2。
有关这一点,请参考烧瓶问题。
溶液
双重逃逸在JavaScript可能是这里的解决办法。path转换器也可以由string代替。
par1 = encodeURIComponent(encodeURIComponent(parameter1));
par2 = encodeURIComponent(encodeURIComponent(parameter2));
$.ajax({
type:'post',
url:'http://localhost:8000/get_data'+'/'+par1+'/'+par2+'/'});并在烧瓶应用程序中解码以取回字符串。
from urllib import unquote_plus
@app.route('/get_data/<string:par1>/<string:par2>/',methods=['GET','POST'])
def get_data(par1, par2):
print unquote_plus(par1), unquote_plus(par1)https://stackoverflow.com/questions/55550575
复制相似问题