Python3+Flask安装使用教程详解


Posted in Python onFebruary 16, 2021

 一、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。结果如下图:

Python3+Flask安装使用教程详解

三、get和post实现

3.1 创建用到的模板文件

Flask默认到templates目录下查找模板文件,在上边helloworld.py同级目录下创建templates文件夹。

在templates文件夹下创建get.html,写入以下内容:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get请求示例</title>
</head>
<body>
 <form action="/deal_request" method="get">
 <input type="text" name="q" />
 <input type="submit" value="搜索" />
 </form>
</body>
</html>

再在templates文件夹下创建post.html,写入以下内容:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>post请求示例</title>
</head>
<body>
 <form action="/deal_request" method="post">
 <input type="text" name="q" />
 <input type="submit" value="搜索" />
 </form>
</body>
</html>

最后在templates文件夹下创建result.html,写入以下内容:

<!-- Flask 使用Jinja2模板引擎,Jinja2模板引擎源于Django板模所以很多语法和Django是类似的 -->
<h1>{{ result }}</h1>

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_url_rule('/', 'helloworld', hello_world)
@app.route('/helloworld')
def hello_world():
 return 'Hello, World!'

# 配置路由,当请求get.html时交由get_html()处理
@app.route('/get.html')
def get_html():
 # 使用render_template()方法重定向到templates文件夹下查找get.html文件
 return render_template('get.html')

# 配置路由,当请求post.html时交由post_html()处理
@app.route('/post.html')
def post_html():
 # 使用render_template()方法重定向到templates文件夹下查找post.html文件
 return render_template('post.html')

# 配置路由,当请求deal_request时交由deal_request()处理
# 默认处理get请求,我们通过methods参数指明也处理post请求
# 当然还可以直接指定methods = ['POST']只处理post请求, 这样下面就不需要if了
@app.route('/deal_request', methods = ['GET', 'POST'])
def deal_request():
 if request.method == "GET":
 # get通过request.args.get("param_name","")形式获取参数值
 get_q = request.args.get("q","")
 return render_template("result.html", result=get_q)
 elif request.method == "POST":
 # post通过request.form["param_name"]形式获取参数值
 post_q = request.form["q"]
 return render_template("result.html", result=post_q)

if __name__ == '__main__':
 # app.run(host, port, debug, options)
 # 默认值:host=127.0.0.1, port=5000, debug=false
 app.run()

3.3 查看运行效果

重新运行helloworld.py。

当前目录结构如下(.idea目录不用管):

Python3+Flask安装使用教程详解

get.html如下:

Python3+Flask安装使用教程详解

get查询结果如下:

Python3+Flask安装使用教程详解

post.html如下:

Python3+Flask安装使用教程详解

post查询结果如下:

Python3+Flask安装使用教程详解

四、restful

所谓restful简单理解就是以json等格式(而非以前的表单格式)发起请求,及以json等格式(而非以前的html)进行响应。

等下我们通过curl模拟rest请求,然后使用jsonify实现rest响应。

4.1 服务端实现代码

# 导入Flask类
from flask import Flask, jsonify
from flask import render_template
from flask import request

# 实例化,可视为固定格式
app = Flask(__name__)

# route()方法用于设定路由;类似spring路由配置
#等价于在方法后写:app.add_url_rule('/', 'helloworld', hello_world)
@app.route('/helloworld')
def hello_world():
 return 'Hello, World!'

# 配置路由,当请求get.html时交由get_html()处理
@app.route('/get.html')
def get_html():
 # 使用render_template()方法重定向到templates文件夹下查找get.html文件
 return render_template('get.html')

# 配置路由,当请求post.html时交由post_html()处理
@app.route('/post.html')
def post_html():
 # 使用render_template()方法重定向到templates文件夹下查找post.html文件
 return render_template('post.html')

# 配置路由,当请求deal_request时交由deal_request()处理
# 默认处理get请求,我们通过methods参数指明也处理post请求
# 当然还可以直接指定methods = ['POST']只处理post请求, 这样下面就不需要if了
@app.route('/deal_request', methods=['GET', 'POST'])
def deal_request():
 if request.method == "GET":
 # get通过request.args.get("param_name","")形式获取参数值
 get_q = request.args.get("q","")
 return render_template("result.html", result=get_q)
 elif request.method == "POST":
 # post通过request.form["param_name"]形式获取参数值
 post_q = request.form["q"]
 return render_template("result.html", result=post_q)

@app.route('/rest_test',methods=['POST'])
def hello_world1():
 """
 通过request.json以字典格式获取post的内容
 通过jsonify实现返回json格式
 """
 post_param = request.json
 result_dict = {
 "result_code": 2000,
 "post_param": post_param
 }
 return jsonify(result_dict)


if __name__ == '__main__':
 # app.run(host, port, debug, options)
 # 默认值:host=127.0.0.1, port=5000, debug=false
 app.run()

4.2 请求模拟

curl -H "Content-Type:application/json" -X POST --data '{"username": "ls","password":"toor"}' http://127.0.0.1:5000/rest_test

4.3 效果截图

Python3+Flask安装使用教程详解

五、Flask与Django比较

5.1 Django配置复杂

如果对Django不是很了解,可以参看

仅从文章长度看就比这篇长很多,所以Django比Flask复杂(得多)是肯定的。更具体比较如下:

比较项 Django Flask 复杂度比较 说明
项目创建 Django需要用命令创建项目 Flask直接编写文件就可运行 Django复杂 Django需要用命令创建项目是因为要创建出整个项目框架
路由 Django使用专门的urls.py文件 Flask直接使用@app.route() Django笨重 Django类似Strut2的配置Flask类似Spring的配置,Flask感觉更好
get和post request.GET['name']和request.POST["name"] request.args.get("name","")和request.form["q"] 差不多 Flask格式上不统一
restful 使用django-resful框架 使用jsonify 差不多 Flask不需要单建一个app,更直观一些
数据库操作 django集成了对数据库的操作 Flask没集成对数据库的操作要另行直连或使用sqlalchemy 差不多 django复杂很大程度来源于对数据库的集成。

5.2 Flask和Django各自适合使用场景

我们经常会听说这样的一个近乎共识的观点:Django是Python最流行的Web框架但配置比较复杂,Flask是一个轻量级的框架配置比较简单如果项目比较小推荐使用Flask。

进一步来说,Flask的轻量来源其“暂时不用的功能都先不做处理”,Django复杂来源于其“可能用到的功能都先集成”;随着项目规模的扩大最终Django有的东西Flask也都需要有。

所以,如果平时你用python是东用一个库西用一个库,东写一个场景西写一个场景,而不是专门开发web,那么你适合使用Flask,因为这样你的学习成本低及以前的知识都能用上去。

本文主要讲解了Python3+Flask安装使用教程如果想查看更多关于Python3+Flask的知识文章请点击下面相关文章

Python 相关文章推荐
初步讲解Python中的元组概念
May 21 Python
详解Python爬虫的基本写法
Jan 08 Python
深入了解Django View(视图系统)
Jul 23 Python
Pytorch抽取网络层的Feature Map(Vgg)实例
Aug 20 Python
python-Web-flask-视图内容和模板知识点西宁街
Aug 23 Python
django创建超级用户过程解析
Sep 18 Python
python实现回旋矩阵方式(旋转矩阵)
Dec 04 Python
浅谈图像处理中掩膜(mask)的意义
Feb 19 Python
Django框架静态文件处理、中间件、上传文件操作实例详解
Feb 29 Python
解决django框架model中外键不落实到数据库问题
May 20 Python
使用Python防止SQL注入攻击的实现示例
May 21 Python
python Scrapy爬虫框架的使用
Jan 21 Python
Python基于爬虫实现全网搜索并下载音乐
Feb 14 #Python
Python LMDB库的使用示例
Feb 14 #Python
python 装饰器重要在哪
Feb 14 #Python
python爬虫如何解决图片验证码
Feb 14 #Python
Python实现粒子群算法的示例
Feb 14 #Python
Python中对象的比较操作==和is区别详析
Feb 12 #Python
python绘图模块之利用turtle画图
Feb 12 #Python
You might like
乱谈我对耳机、音箱的感受
2021/03/02 无线电
基于php(Thinkphp)+jquery 实现ajax多选反选不选删除数据功能
2017/02/24 PHP
PHP实现的curl批量请求操作示例
2018/06/06 PHP
50个优秀经典PHP算法大集合 附源码
2020/08/26 PHP
WordPress伪静态规则设置代码实例
2020/12/10 PHP
看了就知道什么是JSON
2007/12/09 Javascript
jquery焦点图片切换(数字标注/手动/自动播放/横向滚动)
2013/01/24 Javascript
Google (Local) Search API的简单使用介绍
2013/11/28 Javascript
自己实现ajax封装示例分享
2014/04/01 Javascript
jQuery中:disabled选择器用法实例
2015/01/04 Javascript
深入理解JavaScript系列(33):设计模式之策略模式详解
2015/03/03 Javascript
JS实现动态移动层及拖动浮层关闭的方法
2015/04/30 Javascript
基于bootstrap3和jquery的分页插件
2015/07/31 Javascript
微信小程序 常用工具类详解及实例
2017/02/15 Javascript
JS使用贪心算法解决找零问题示例
2017/11/27 Javascript
js实现点击展开隐藏效果(实例代码)
2018/09/28 Javascript
Vue 动态组件与 v-once 指令的实现
2019/02/12 Javascript
[37:50]VP vs TNC Supermajor小组赛B组 BO3 第一场 6.2
2018/06/03 DOTA
使用Python3编写抓取网页和只抓网页图片的脚本
2015/08/20 Python
python使用turtle库绘制时钟
2020/03/25 Python
python安装pywin32clipboard的操作方法
2019/01/24 Python
详解python校验SQL脚本命名规则
2019/03/22 Python
学习和使用python的13个理由
2019/07/30 Python
使用python模拟命令行终端的示例
2019/08/13 Python
学Python 3的理由和必要性
2019/11/19 Python
django 模型中的计算字段实例
2020/05/19 Python
python为什么要安装到c盘
2020/07/20 Python
scrapy redis配置文件setting参数详解
2020/11/18 Python
TripAdvisor斯洛伐克:阅读评论、比较价格和酒店预订
2018/04/25 全球购物
以思科路由器为例你写下单臂路由的配置命令
2013/08/03 面试题
劳动模范事迹材料
2014/01/19 职场文书
《小石潭记》教学反思
2014/02/13 职场文书
老人与海读书笔记
2015/06/26 职场文书
python 如何用map()函数创建多线程任务
2021/04/07 Python
聊一聊python常用的编程模块
2021/05/14 Python
python 管理系统实现mysql交互的示例代码
2021/12/06 Python