我们之前的视图函数,返回的都是简单的'Hello Wolrd'
之类的字符串,怎么返回一个html呢?首先我们在templates文件夹建立一个html文件,内容随便写一点如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>This is index page</h1>
</body>
</html>
我们可以使用Flask
对象app
的send_static_file
方法,使视图函数返回一个静态的html文件,但现在我们不使用这种方法,而是使用flask
的render_template
函数,它功能更强大。
从flask
中导入render_template
,整体代码如下:
from flask import Flask, render_template
import config
app = Flask(__name__)
app.config.from_object(config)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
render_template
函数会自动在templates文件夹中找到对应的html,因此我们不用写完整的html文件路径。用浏览器访问'/'
这个地址