关于网友提出的“(python)flask中关于url_for的问题”问题疑问,本网通过在网上对“(python)flask中关于url_for的问题”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题:(python)flask中关于url_for的问题
描述:问题
有变量date='12/2015'
,使用url_for('main.index', date = date)
会产生如localhost:5000/12/2015
的地址,于是乎出现
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
这样的错误。实际上我想产生的地址在浏览器上看着应该是这样的localhost:5000/12%2F2015
。就是想把那个日期作为请求放在url中,但是由于斜线的存在而出现了这样的错误。不知如何解决,忘大家赐教。
源代码
@main.route('/', defaults = {'date': ''})
@main.route('/')
def index(date):
cur_path = os.getcwd()
path = os.path.join(cur_path, 'app/upload')
files = os.listdir(path)
if date:
file_abspath = os.path.join(path, date.split('/')[1] + date.split('/')[0] + '.xlsx')
else:
file_abspath = os.path.join(path, files[len(files) - 1])
opxl = Opxl()
brief_info = opxl.get_brief_info(file_abspath)
return render_template('brief.html', brief_info = brief_info)
@main.route('/search_brief')
def search_brief():
date = request.args.get('date') # 这里的date类似12/2015
filenamewithext = date.split('/')[1] + date.split('/')[0] + '.xlsx'
path = os.path.join(os.getcwd(), 'app/upload')
files = os.listdir(path)
if filenamewithext not in files:
flash('不存在对应日期的记录')
return redirect(url_for('main.index'))
else:
return redirect(url_for('main.index', date = date))
主要是第二个函数的代码
解决方案1:date = date | replace('/','')
解决方案2:既然后台需要使用split,那你在传递变量的时候可以
date = date | replace('/','-')
解决方案3:urllib.parse
标准库里面有一个函数:quote_plus
,可以把这类字符串转换为URL中可以使用的字符。下面是这个函数的介绍:
urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)
Like quote(), but also replace spaces by plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.
Example: quote_plus('/El Ni駉/') yields '%2FEl+Ni%C3%B1o%2F'.
解决方案4:@app.route('/loadfile/')
path 不就是为了这种情况设置的么。。。。
http://www.pythondoc.com/flask/quickstart.html#id5
以上介绍了“(python)flask中关于url_for的问题”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/1456912.html