You need to enable JavaScript to run this app. Flask部署OVH服务器后调用render_template加载模板报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Flask部署OVH服务器后调用render_template加载模板报错如何解决?

Flask模板返回配置解决方案

1. 明确指定模板目录绝对路径

OVH服务器运行Python应用时默认工作目录可能与www目录不一致,导致Flask无法找到默认位置的templates文件夹,修改myapp.py中Flask实例的初始化代码,强制绑定模板路径:

import os

this_file = "venv/bin/activate_this.py"
exec(open(this_file).read(), {'__file__': this_file})

from flask import Flask, render_template

# 获取当前脚本所在目录的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 明确指定模板文件夹路径
application = Flask(__name__, template_folder=os.path.join(BASE_DIR, 'templates'))

@application.route('/')
@application.route('/index')
def index():
    return render_template('index.html')

2. 确认目录结构与权限

使用如下正确目录结构:

www/
  venv/
  myapp.py
  templates/
    index.html

调整文件权限:

  • templates文件夹权限设置为755
  • 文件夹内的index.html文件权限设置为644
    确保Web服务进程拥有模板文件的读取权限。

3. 临时开启调试排查问题

如果修改后仍报错,可临时开启调试模式查看具体错误信息:

application.config['DEBUG'] = True

注意:问题排查完成后必须关闭DEBUG模式,避免生产环境泄露敏感信息。

4. 优化虚拟环境激活路径(可选)

也可以将虚拟环境激活文件的路径修改为绝对路径,避免相对路径读取错误:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
this_file = os.path.join(BASE_DIR, "venv/bin/activate_this.py")
exec(open(this_file).read(), {'__file__': this_file})

内容的提问来源于stack exchange,提问作者Guliup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 20:57:04