首页 > 解决方案 > `app.route` 和 `template_render` 在 Flask 中不起作用

问题描述

我正在学习 Flask 并创建了两条路线:

  1. "/about" : 将模板路由为 render.template(about.html)
  2. "/aksh" : 将模板路由为 render.template(index.html)

它有效index.html但无效about.html,当我进行更改index.html并刷新时,什么也没发生。我尝试重新启动一切,包括我的系统。

然后我评论了那条路线“/aksh”,但令我惊讶的是,portaddress/about 显示没有找到 url,而 portaddress/aksh 仍在显示文本。

之后我重新编辑了整个代码,现在在新代码中有 3 条路线:

  1. “/”:返回打印语句“Hello World!”
  2. "/aksh" : 渲染一个模板index.html
  3. "/about" : 渲染一个模板about.html

但这现在没有改变,我也得到了旧的结果,新的路线没有得到更新。

我的python代码是:

from flask import Flask,render_template
app=Flask(__name__)
@app.route("/")
def hello():
    return "Hello World"
@app.route("/aksh")
def aksh():
    return render_template('index.html')
@app.route("/about")
def about():
    return render_template('about.html')
app.run(debug=True)

index 和 about 的 HTML 代码是: index.html :

<html>
<head>
    <meta charset="utf-8">
    <title>Title of my page</title>
</head>
<body>
<p>We are testing flask app here</p>
</body>
</html>

对于 about.html :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>About this page</title>
</head>
<body>
<h1>This is about section</h1>
</body>
</html>

它显示“我们正在测试应用程序”,但它必须是“我们正在测试应用程序,而且它的位置错误,它必须在路线“/aksh”而不是“/” 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

标签: pythonflaskflask-sqlalchemy

解决方案


使用分隔符来解决这个问题。

from flask import Flask,render_template
app=Flask(__name__)


@app.route("/")
def hello():
    return "Hello World"


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


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


app.run(debug=True)

推荐阅读