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('/<date>')
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))

主要是第二个函数的代码

阅读 15.4k
4 个回答

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'.

既然后台需要使用split,那你在传递变量的时候可以

date = date | replace('/','-')

date = date | replace('/','')

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题