赞
踩
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()
-
-

- @app.route('/request1', methods=['GET'])
- def post1():
- name = request.args.get('name') #方式1
-
- data = {'age': 18, 'name': name}
- return jsonify(data)
如图
postman指定get请求
name = request.form.get('name') #使用这种方式接收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));
- }
- });

- 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)
- #定义蓝图
- 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’ 是否可以省略
答案:不可以,必须设置,并且需要唯一。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。