Flask 是一个轻量级的 Web 框架,用于 Python 编程语言。它旨在快速、简单、灵活地开发 Web 应用程序。
快速开始
安装 Flask 使用 pip 安装 Flask:
pip install flask
创建 Flask 应用
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == '__main__': app.run()
运行应用
在终端中运行上述脚本,默认情况下 Flask 应用于
127.0.0.1:5000
。
路由和视图函数
Flask 使用 @app.route()
装饰器来创建路由。每个路由对应一个视图函数。
示例
@app.route('/')
def index():
return 'Welcome to the index page!'
@app.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'
模板
Flask 使用 Jinja2 作为其模板引擎。模板文件通常位于 templates
目录中。
示例
创建一个名为 index.html
的模板文件:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Welcome{% endblock %}</title>
</head>
<body>
{% block content %}Default content{% endblock %}
</body>
</html>
在视图函数中使用模板:
from flask import render_template
@app.route('/')
def index():
return render_template('index.html', title='Index Page', content='Welcome to the index page!')
图片
Flask Logo
注意事项
- 确保不要在 Flask 应用中包含任何敏感信息。
- 在生产环境中,请使用 HTTPS。