【问题标题】:Flask cannot find templateFlask 找不到模板
【发布时间】:2020-06-13 14:31:40
【问题描述】:

我有 python 代码,我想显示一个 html 页面:

我收到错误返回 render_template('index.html')

我已尝试指定模板文件夹,但它也不起作用。

我的项目目录:

/api
-- api.py
-- /templates
---- index.html

我也在运行服务器,例如: 烧瓶运行 -h 192.168.x.x -p 8080

jinja2.exceptions.TemplateNotFound: index.html
- - [29/Feb/2020 20:35:20] "GET / HTTP/1.1" 500 -


   from flask import Flask, render_template
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
app = Flask("__main__")
pwm = GPIO.PWM(3, 50)
pwm.start(0)

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

@app.route('/switch/<val>')
def switch(val):
    if val == "on":
        SetAngle(0)
    elif val == "off":
        SetAngle(180)
    return

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


def SetAngle(angle):
    duty = angle / 18 + 2
    GPIO.output(3, True)
    pwm.ChangeDutyCycle(duty)
    sleep(1)
    GPIO.output(3, False)
    pwm.ChangeDutyCycle(0)

【问题讨论】:

  • 设置app.config['EXPLAIN_TEMPLATE_LOADING'] = True 来检查flask 在哪里寻找你的模板。它说什么?

标签: python python-3.x flask


【解决方案1】:

您是否使用“/templates/index.py”指定了文件?如果是这样,python 会认为模板目录位于文件系统的根目录 '/',而不是写 'templates/index.py'。

如果您在 Windows 上工作,您可能必须将 / 替换为 \,在这种情况下,您应该编写 'templates\index.py'。

【讨论】:

    【解决方案2】:

    从您的代码中可以看出,一切都应该正常工作!但如果不是,那么合理的答案是您可能使用了损坏/篡改的烧瓶版本,或者您一定拼错了某些东西。希望这能解决问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2017-08-13
      • 2021-04-05
      • 2020-02-26
      • 1970-01-01
      相关资源
      最近更新 更多