python - flask中关于url_for的问题
大家讲道理
大家讲道理 2017-04-17 17:28:34
[Python讨论组]

问题
有变量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))

主要是第二个函数的代码

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(4)
巴扎黑

@app.route('/loadfile/<path:path>')
path 不就是为了这种情况设置的么。。。。
http://www.pythondoc.com/flask/quickstart.html#id5

怪我咯

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号