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如何使用正则表达式的前向、后向搜索及前向搜索否定模式详解
Nov 08 Python
python决策树之C4.5算法详解
Dec 20 Python
Python request设置HTTPS代理代码解析
Feb 12 Python
用Python编写一个简单的CS架构后门的方法
Nov 20 Python
python爬虫selenium和phantomJs使用方法解析
Aug 08 Python
wxpython实现按钮切换界面的方法
Nov 19 Python
浅谈keras的深度模型训练过程及结果记录方式
Jan 24 Python
python range实例用法分享
Feb 06 Python
40行Python代码实现天气预报和每日鸡汤推送功能
Feb 27 Python
python利用线程实现多任务
Sep 18 Python
python编程的核心知识点总结
Feb 08 Python
python的变量和简单数字类型详解
Sep 15 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
PHP 字符截取 解决中文的截取问题,不用mb系列
2009/09/29 PHP
ThinkPHP 3.2.3实现页面静态化功能的方法详解
2017/08/03 PHP
Laravel创建数据库表结构的例子
2019/10/09 PHP
Yii 框架使用Forms操作详解
2020/05/18 PHP
jQuery live
2009/05/15 Javascript
js中的数组Array定义与sort方法使用示例
2013/08/29 Javascript
QQ空间顶部折页撕开效果示例代码
2014/06/15 Javascript
简单介绍JavaScript的变量和数据类型
2015/06/03 Javascript
JS实现仿新浪微博发布内容为空时提示功能代码
2015/08/19 Javascript
JavaScript简单获取系统当前时间完整示例
2016/08/02 Javascript
关于redux-saga中take使用方法详解
2018/02/27 Javascript
微信小程序实现自定义modal弹窗封装的方法
2018/06/15 Javascript
VUE中v-on:click事件中获取当前dom元素的代码
2018/08/22 Javascript
vue Cli 环境删除与重装教程 - 版本文档
2020/09/11 Javascript
vue实现一个矩形标记区域(rectangle marker)的方法
2020/10/28 Javascript
python打开文件并获取文件相关属性的方法
2015/04/23 Python
Python基于正则表达式实现文件内容替换的方法
2017/08/30 Python
Python 多核并行计算的示例代码
2017/11/07 Python
解决Python3 被PHP程序调用执行返回乱码的问题
2019/02/16 Python
python浪漫表白源码
2019/04/05 Python
jenkins配置python脚本定时任务过程图解
2019/10/29 Python
TensorFlow:将ckpt文件固化成pb文件教程
2020/02/11 Python
python:批量统计xml中各类目标的数量案例
2020/03/10 Python
OpenCV+Python3.5 简易手势识别的实现
2020/12/21 Python
HTML5中5个简单实用的API(第二篇,含全屏、可见性、拍照、预加载、电池状态)
2014/05/07 HTML / CSS
主办会计岗位职责
2014/03/13 职场文书
预防煤气中毒方案
2014/06/16 职场文书
2014幼儿园教师师德师风演讲稿
2014/09/10 职场文书
2014教师“四风问题”对照检查材料思想汇报
2014/09/16 职场文书
个人诉讼委托书范本
2014/10/17 职场文书
党的群众路线教育实践活动学习笔记
2014/11/05 职场文书
2015年社区妇联工作总结
2015/04/21 职场文书
隐形的翅膀观后感
2015/06/10 职场文书
幼儿园2016年圣诞活动总结
2016/03/31 职场文书
创业计划书之孕婴生活馆
2019/11/11 职场文书
浅析MySQL如何实现事务隔离
2021/06/26 MySQL