首页 > Python资料 博客日记
python篇-常用库08-Flask框架(图文详解)
2024-07-30 02:00:06Python资料围观77次
这篇文章介绍了python篇-常用库08-Flask框架(图文详解),分享给大家做个参考,收藏Python资料网收获更多编程知识
一、 简介
Flask是一个非常小的PythonWeb框架,被称为微型框架;只提供了一个稳健的核心,其他功能全部是通过扩展实现的。
二、 概要
安装: pip install flask
使用到装饰器:以@开头的代码方法
三、 实例如下
from flask import Flask, request, jsonify
# 用当前脚本名称实例化Flask对象,方便flask从该脚本文件中获取需要的内容
app = Flask(__name__)
#在Flask中,路由是通过@app.route装饰器(以@开头)来表示
@app.route("/")
def index():
return "Hello World!"
#methods参数用于指定允许的请求格式,#常规输入url的访问就是get方法
@app.route("/hello",methods=['GET','POST'])
def hello():
return "Hello World!"
#注意路由路径不要重名,映射的视图函数也不要重名
@app.route("/hi",methods=['POST'])
def hi():
return "Hi World!"
#指定参数
#string 接受任何不包含斜杠的文本
#int 接受正整数
#float 接受正浮点数
#path 接受包含斜杠的文本
@app.route("/index/<int:id>",)
def index_args(id):
if id == 1:
return 'first'
elif id == 2:
return 'second'
elif id == 3:
return 'thrid'
else:
return 'hello world!'
#request对象的使用
@app.route("/index/request",)
def index_request():
if request.method == 'GET':
return render_template('index.html')
elif request.method == 'POST':
name = request.form.get('name')
password = request.form.get('password')
return name+" "+password
#请求钩子before_request/after_request
#想要在正常执行的代码的前、中、后时期,强行执行一段我们想要执行的功能代码,便要用到钩子函数---用特#定装饰器装饰的函数。
@app.before_request
def before_request_a():
print('I am in before_request_a')
@app.before_request
def before_request_b():
print('I am in before_request_b')
#before_first_request:与before_request的区别是,只在第一次请求之前调用;
#after_request:每一次请求之后都会调用;
#teardown_request:每一次请求之后都会调用;
#after_request、teardown_request 钩子函数表示每一次请求之后,可以执行某个特定功能的函数,这个函数接收response对象,所以执行完后必须归还response对象;
#执行的顺序是先绑定的后执行;
@app.after_request
def after_request_a(response):
print('I am in after_request_a')
# 该装饰器接收response参数,运行完必须归还response,不然程序报错
return response
#redirect重定向,应该配合url_for函数来使用
@app.route('/redirect_index')
def index():
# redirect重定位(服务器向外部发起一个请求跳转)到一个url界面;
# url_for给指定的函数构造 URL;
# return redirect('/hello') 不建议这样做,将界面限死了,应该如下写法
return redirect(url_for('hello'))
#返回json数据给前端
@app.route("/web_index")
def index():
data = {
'name':'张三'
}
return jsonify(data)
# 启动http服务
app.run()
四、补充
1、浏览器的get请求,使用args参数接收
@app.route('/request1', methods=['GET'])
def post1():
name = request.args.get('name') #方式1
data = {'age': 18, 'name': name}
return jsonify(data)
如图
postman指定get请求
2、浏览器的post请求,使用form参数接收
name = request.form.get('name') #使用这种方式接收name参数
3、浏览器的post请求,可是使用request.json.get("name")获取
需要浏览器发送的请求头指定为:headers: {'Content-Type': 'application/json'}
HTTP接口获取数据
@app.route('/save', methods=['post'])
def save():
user = request.json.get("user")
print("user=", user)
pw = request.json.get("pass")
print("pass=", pw)
print("请求成功,请求路径为/save")
json_dict = {'user': user, 'pass': pw}
# 使用jsonify来讲定义好的数据转换成json格式,并且返回给前端
return jsonify(json_dict)
前端request接口请求jquery设置header:
var params={"user":"长官三","pass":"1234"}
var jsonData = JSON.stringify(params);//转为json字符串
$.ajax({
url: "http://localhost:5000/save",
method: 'post',
// 通过headers对象设置请求头
headers: {
'Content-Type': 'application/json'
},
data:jsonData,
dataType:'json',
success:function (data, status, params) {
alert(data.user)
alert(data.pass)
$("#test1").text(JSON.stringify(data));
}
});
4、使用flask的 jsonify方法,将定义好的数据转换成json格式,并返回给前端
from flask import Flask, jsonify, request
@app.route('/student', methods=['get', 'post'])
def student():
print("请求成功,请求路径为/student")
json_dict = {'name': '张三', 'age': 10, '性别': '男'}
# 使用jsonify来讲定义好的数据转换成json格式,并且返回给前端
return jsonify(json_dict)
五、flask配合blueprint蓝图使用,方便路由管理
#定义蓝图
webjs = Blueprint('data-factory/webjs', __name__)
#蓝图的路由函数
@webjs.route('/webjs/addRecord', methods=['POST'])
def addRecord():
login_role = request.json.get("login_role")
app_version = request.json.get("app_version")
login_account = request.json.get("login_account")
res = SQlWebjs().insertRecord(login_role, app_version, login_account, device_name, device_serial, data,
coverage_type, coverage_report_type, url, description)
return jsonify({"code": 0, "msg": "查询完成",
"data": {
"result": res,
}
})
#汇总所有的蓝图,注册到app中(方便路由管理)
app = Flask(__name__)
app.register_blueprint(webjs)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080, debug=True)
webjs = Blueprint('shw', __name__)
疑问:定义蓝图的第一个参数‘shw’ 是否可以省略
答案:不可以,必须设置,并且需要唯一。
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- 光流法结合深度学习神经网络的原理及应用(完整代码都有Python opencv)
- Python 图像处理进阶:特征提取与图像分类
- 大数据可视化分析-基于python的电影数据分析及可视化系统_9532dr50
- 【Python】入门(运算、输出、数据类型)
- 【Python】第一弹---解锁编程新世界:深入理解计算机基础与Python入门指南
- 华为OD机试E卷 --第k个排列 --24年OD统一考试(Java & JS & Python & C & C++)
- Python已安装包在import时报错未找到的解决方法
- 【Python】自动化神器PyAutoGUI —告别手动操作,一键模拟鼠标键盘,玩转微信及各种软件自动化
- Pycharm连接SQL Sever(详细教程)
- Python编程练习题及解析(49题)
点击排行
- 版本匹配指南:Numpy版本和Python版本的对应关系
- 版本匹配指南:PyTorch版本、torchvision 版本和Python版本的对应关系
- Python 可视化 web 神器:streamlit、Gradio、dash、nicegui;低代码 Python Web 框架:PyWebIO
- 相关性分析——Pearson相关系数+热力图(附data和Python完整代码)
- Anaconda版本和Python版本对应关系(持续更新...)
- Python与PyTorch的版本对应
- Windows上安装 Python 环境并配置环境变量 (超详细教程)
- Python pyinstaller打包exe最完整教程