当前位置:   article > 正文

python篇-常用库08-Flask框架(图文详解)_pythonflask框架

pythonflask框架

一、 简介

Flask是一个非常小的PythonWeb框架,被称为微型框架;只提供了一个稳健的核心,其他功能全部是通过扩展实现的。

二、 概要

安装: pip install flask
使用到装饰器:以@开头的代码方法

三、 实例如下

  1. from flask import Flask, request, jsonify
  2. # 用当前脚本名称实例化Flask对象,方便flask从该脚本文件中获取需要的内容
  3. app = Flask(__name__)
  4. #在Flask中,路由是通过@app.route装饰器(以@开头)来表示
  5. @app.route("/")
  6. def index():
  7. return "Hello World!"
  8. #methods参数用于指定允许的请求格式,#常规输入url的访问就是get方法
  9. @app.route("/hello",methods=['GET','POST'])
  10. def hello():
  11. return "Hello World!"
  12. #注意路由路径不要重名,映射的视图函数也不要重名
  13. @app.route("/hi",methods=['POST'])
  14. def hi():
  15. return "Hi World!"
  16. #指定参数
  17. #string 接受任何不包含斜杠的文本
  18. #int 接受正整数
  19. #float 接受正浮点数
  20. #path 接受包含斜杠的文本
  21. @app.route("/index/<int:id>",)
  22. def index_args(id):
  23. if id == 1:
  24. return 'first'
  25. elif id == 2:
  26. return 'second'
  27. elif id == 3:
  28. return 'thrid'
  29. else:
  30. return 'hello world!'
  31. #request对象的使用
  32. @app.route("/index/request",)
  33. def index_request():
  34. if request.method == 'GET':
  35. return render_template('index.html')
  36. elif request.method == 'POST':
  37. name = request.form.get('name')
  38. password = request.form.get('password')
  39. return name+" "+password
  40. #请求钩子before_request/after_request
  41. #想要在正常执行的代码的前、中、后时期,强行执行一段我们想要执行的功能代码,便要用到钩子函数---用特#定装饰器装饰的函数。
  42. @app.before_request
  43. def before_request_a():
  44. print('I am in before_request_a')
  45. @app.before_request
  46. def before_request_b():
  47. print('I am in before_request_b')
  48. #before_first_request:与before_request的区别是,只在第一次请求之前调用;
  49. #after_request:每一次请求之后都会调用;
  50. #teardown_request:每一次请求之后都会调用;
  51. #after_request、teardown_request 钩子函数表示每一次请求之后,可以执行某个特定功能的函数,这个函数接收response对象,所以执行完后必须归还response对象;
  52. #执行的顺序是先绑定的后执行;
  53. @app.after_request
  54. def after_request_a(response):
  55. print('I am in after_request_a')
  56. # 该装饰器接收response参数,运行完必须归还response,不然程序报错
  57. return response
  58. #redirect重定向,应该配合url_for函数来使用
  59. @app.route('/redirect_index')
  60. def index():
  61. # redirect重定位(服务器向外部发起一个请求跳转)到一个url界面;
  62. # url_for给指定的函数构造 URL;
  63. # return redirect('/hello') 不建议这样做,将界面限死了,应该如下写法
  64. return redirect(url_for('hello'))
  65. #返回json数据给前端
  66. @app.route("/web_index")
  67. def index():
  68. data = {
  69. 'name':'张三'
  70. }
  71. return jsonify(data)
  72. # 启动http服务
  73. app.run()

四、补充

1、浏览器的get请求,使用args参数接收
  1. @app.route('/request1', methods=['GET'])
  2. def post1():
  3. name = request.args.get('name') #方式1
  4. data = {'age': 18, 'name': name}
  5. 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接口获取数据

  1. @app.route('/save', methods=['post'])
  2. def save():
  3. user = request.json.get("user")
  4. print("user=", user)
  5. pw = request.json.get("pass")
  6. print("pass=", pw)
  7. print("请求成功,请求路径为/save")
  8. json_dict = {'user': user, 'pass': pw}
  9. # 使用jsonify来讲定义好的数据转换成json格式,并且返回给前端
  10. return jsonify(json_dict)

前端request接口请求jquery设置header:

  1. var params={"user":"长官三","pass":"1234"}
  2. var jsonData = JSON.stringify(params);//转为json字符串
  3. $.ajax({
  4. url: "http://localhost:5000/save",
  5. method: 'post',
  6. // 通过headers对象设置请求头
  7. headers: {
  8. 'Content-Type': 'application/json'
  9. },
  10. data:jsonData,
  11. dataType:'json',
  12. success:function (data, status, params) {
  13. alert(data.user)
  14. alert(data.pass)
  15. $("#test1").text(JSON.stringify(data));
  16. }
  17. });

4、使用flask的 jsonify方法,将定义好的数据转换成json格式,并返回给前端
  1. from flask import Flask, jsonify, request
  2. @app.route('/student', methods=['get', 'post'])
  3. def student():
  4. print("请求成功,请求路径为/student")
  5. json_dict = {'name': '张三', 'age': 10, '性别': '男'}
  6. # 使用jsonify来讲定义好的数据转换成json格式,并且返回给前端
  7. return jsonify(json_dict)

五、flask配合blueprint蓝图使用,方便路由管理

  1. #定义蓝图
  2. webjs = Blueprint('data-factory/webjs', __name__)
  3. #蓝图的路由函数
  4. @webjs.route('/webjs/addRecord', methods=['POST'])
  5. def addRecord():
  6. login_role = request.json.get("login_role")
  7. app_version = request.json.get("app_version")
  8. login_account = request.json.get("login_account")
  9. res = SQlWebjs().insertRecord(login_role, app_version, login_account, device_name, device_serial, data,
  10. coverage_type, coverage_report_type, url, description)
  11. return jsonify({"code": 0, "msg": "查询完成",
  12. "data": {
  13. "result": res,
  14. }
  15. })
  16. #汇总所有的蓝图,注册到app中(方便路由管理)
  17. app = Flask(__name__)
  18. app.register_blueprint(webjs)
  19. if __name__ == '__main__':
  20. app.run(host="0.0.0.0", port=8080, debug=True)
webjs = Blueprint('shw', __name__)

疑问:定义蓝图的第一个参数‘shw’ 是否可以省略

答案:不可以,必须设置,并且需要唯一。

参考文档: 如何理解 flask 中的 Blueprint 的 name 参数 - 简书 (jianshu.com)

参考文档:Flask框架入门教程(非常详细)从零基础入门到精通,看完这一篇就够了-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/741834
推荐阅读
相关标签
  

闽ICP备14008679号