问题
flask部署到服务器后app.py中的static相对路径失效。
从日志中可以看到报错为FileNotFoundError: [Errno 2] No such file or directory: 'static/XXX'。
例如我代码中path = './static/module/best.pt'运行后遇到的报错FileNotFoundError: [Errno 2] No such file or directory: 'static/module/best.pt'
之前查到一种方法是获取当前路径然后加到每一处相对路径前面
basedir = os.path.abspath(os.path.dirname(__file__))
path = basedir + 'static/module/best.pt'
就在我痛苦的一个一个在相对路径面前加basedir的时候突然反应过来,我直接用os.chdir()改变当前的工作目录,定义成这个app.py的路径位置不就好了
例如我的app.py的存放路径为/www/wwwroot/flask_cs/
os.chdir('/www/wwwroot/flask_cs/')
在app.py开头添加os.chdir(),把其中的路径改为自己app.py的存放路径即可
这样和上面那种挨个加本质没什么区别就是快捷一点