【问题标题】:Unable to import template无法导入模板
【发布时间】:2021-08-14 13:45:02
【问题描述】:

我是 Flask 初学者,如果我的问题的答案很明显,请见谅。

我一直在使用 OVH 服务器处理一个项目。我一直在使用本教程设置第一个“Hello world”:https://docs.ovh.com/gb/en/web-power/python-install-flask/

这是我的项目的结构:

www/
  venv/
  myapp.py

此时,一切正常。当我连接到我的网站时,它显示了一个很好的“你好,世界!”正如预期的那样。 但是我现在想在我的页面中添加一个模板,因此我添加了几行:

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

from flask import Flask, render_template

application = Flask(__name__)

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

我已经导入了 render_template 并从“return 'Hello'”更改为“return render_template('index.html')”。

很遗憾,我的网站现在显示“从应用程序收到不完整的响应”。我尝试了这两种结构:

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

和:

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

但它并没有改变任何东西......有谁知道如何返回模板?

【问题讨论】:

  • 在 cmd 中激活您的环境,然后在那里运行您的应用程序,不要使用exec,尤其是在不需要它的情况下,我很确定它不需要

标签: python templates flask


【解决方案1】:

而不是从程序中启动 venv

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

(仅适用于 mac/Linux)您可能希望在终端中执行此操作, 作为

venv/bin/activate

来源:https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/

然后,要运行您的文件,您可以添加以下内容:

from flask import Flask, render_template

application = Flask(__name__)

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

if __name__ == '__main__':
    application.run(debug=True)

最后几行是此类项目的好习惯,打开调试器非常有用。你的结构很好。我理解你为什么要添加前几行,我也在开发一个 venv 烧瓶应用程序。但是,我尝试实现这些行的 windows 版本,但没有成功......即使这对你来说很好,请考虑添加

if __name__ == '__main__':
    application.run(debug=True)

不管怎样。

【讨论】:

  • 感谢您的回答!我添加了 ''' if name == 'main': application.run(debug=True)'''。关于this_file = "venv/bin/activate_this.py" exec(open(this_file).read(), {'__file__': this_file}),如果我删除这段代码,它就不再起作用了......即使通过ssh连接到我的服务器时我已经运行了代码source venv/bin/activate......你知道为什么吗?
  • 这似乎与我使用OVH云网络服务器有关。当我在本地服务器上工作时,我不需要添加this_file = "venv/bin/activate_this.py" exec(open(this_file).read(), {'__file__': this_file}),我可以毫无问题地加载模板......
  • @Guliup 老实说,你在服务器上的工作比我还远,我还不知道如何处理这些事情。我已经尝试在测试文件中实现这些行,但这正是它对我来说崩溃的原因......所以我会说删除这些行,但如果这是你唯一的选择......最后一个选项可能是 venv\Lib\activatevenv\Lib\activate.bat 但我只知道这些
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多