模板渲染其实就是静态文件的展示
app.py
import os
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return 'flask home2'
@app.route('/index/')
def index():
# #返回字符串
# return '<b>flask home2</b>'
# #模板渲染
return render_template('index.html', name='小新')
# # #返回json
# # jsonify: 将字典转换为json格式
# return jsonify({'name': '小新', 'age': 18})
if __name__ == '__main__':
# print(f"Starting server on port {os.environ.get('FLASK_RUN_PORT', 'not set')}")
# app.run(debug=True, port=5001, host='0.0.0.0')
port = 8884
print(f"Starting Flask server on port {port}")
app.run(debug=True, port=port, host='0.0.0.0')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板渲染</title>
{#导入css文件、这里css文件名最好和html文件名一致#}
{#3种导入静态文件的方式#}
{# <link rel="stylesheet" href="../static/index.css">#}
{# <link rel="stylesheet" href="/static/index.css">#}
<link rel="stylesheet", href="{{ url_for('static', filename='index.css') }}">
</head>
<body>
<h1>模板渲染</h1>
<hr>
{#name 变量是从app.py中return 传过来的变量名#}
<h2>{{ name }}</h2>
</body>
</html>
index.css
/*这里h2是指在html中的h2标签,html中使用h2标签中的内容会变成红色*/
h2 {
color: red;
}