Flask 直接顯示根目錄文件內容

搜索結果json

@app.route('/<path>')
def info(path):
    resp = make_response(open(path).read())
    resp.headers["Content-type"]="application/json;charset=UTF-8"
    return resp


按道理應該是能夠生效的,但我在用的時候卻報錯了app

出現錯誤
IOError: [Errno 2] No such file or directory: u'readme.json'
竟然找不到這個文件code

解決辦法
使用絕對路徑io

@app.route('/<path>')
def today(path):
    base_dir = os.path.dirname(__file__)
    resp = make_response(open(os.path.join(base_dir, path)).read())
    resp.headers["Content-type"]="application/json;charset=UTF-8"
    return resp


訪問 127.0.0.1:5000/readme.jsonclass

相關文章
相關標籤/搜索