Flask安装
建议在Python虚拟环境中安装
第一个Flask程序
1 2 3 4 5 6 7 8 9 10 11 12
| from flask import Flask
app = Flask(__name__)
@app.route("/") def hello_world(): return "Hello, World!"
if __name__ == "__main__": app.run(debug=True)
|
在浏览器中访问http://127.0.0.1:5000
路由
route()
使用route()装饰器来把函数绑定到 URL
1 2 3 4 5 6 7
| @app.route('/') def index(): return 'Index Page'
@app.route('/hello') def hello(): return 'Hello, World'
|
路由参数
<variable_name>路由参数
通过<>标记的变量作为参数传递给函数。
1 2 3
| @app.route("/user/<name>") def hello_world(name): return "name is:"+name
|

converter:variable_name参数类型
通过转换器converter为参数指定类型。默认类型为string即字符串。
1 2 3
| @app.route("/id/<int:id>") def bandid(id): return "id is: "+str(id)
|

转换器类型
| converter |
描述 |
| string |
文本 |
| int |
整数 |
| float |
浮点数 |
| path |
路径 |
| uuid |
UUID字符串 |
请求方式
通过定义路由来指定请求方式,Flask默认将路由处理为GET请求。
1 2 3 4 5 6 7
| @app.route("/hello", methods=["GET"]) def hello(): return "Hello, World!"
@app.route("/submit", methods=["POST"]) def submit(): return "Data Submitted!"
|
Jinja2模板引擎