一、Flask安装环境配置
当前我的开发环境是Miniconda3+PyCharm。开发环境其实无所谓,自己使用Python3+Nodepad都可以。安装Flask库:
pip install Flask
二、第一个Flask应用程序
将以下内容保存为helloworld.py:
# 导入Flask类
from flask import Flask
# 实例化,可视为固定格式
app = Flask(__name__)
# route()方法用于设定路由;类似spring路由配置
@app.route('/helloworld')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
# app.run(host, port, debug, options)
# 默认值:host="127.0.0.1", port=5000, debug=False
app.run(host="0.0.0.0", port=5000)
直接运行该文件,然后访问:http://127.0.0.1:5000/helloworld。结果如下图:
三、get和post实现
3.1 创建用到的模板文件
Flask默认到templates目录下查找模板文件,在上边helloworld.py同级目录下创建templates文件夹。
在templates文件夹下创建get.html,写入以下内容:
get请求示例再在templates文件夹下创建post.html,写入以下内容:
post请求示例最后在templates文件夹下创建result.html,写入以下内容:
{ { result }}
3.2 编写相关的处理方法
在helloworld.py中添加get_html()、post_html()和deal_request()三个方法,更多说明见注释。当前helloworld.py内容如下:
# 导入Flask类
from flask import Flask
from flask import render_template
from flask import request
# 实例化,可视为固定格式
app = Flask(__name__)
# route()方法用于设定路由;类似spring路由配置
#等价于在方法后写:app.add_