flask_1:简介及基本概念—视图/路由/模版/模型/MVC/中间件
下面2篇博客非常详尽的介绍了flask的基本概念
(2)Flask视图
from flask import Flask from flask import render_template, jsonify, make_response, session, redirect, url_for import templates from flask import request, jsonify, current_app as app app = Flask(__name__, template_folder=templates) app.config['DEBUG'] = True app.secret_key = 'itheima' username = '回旋' @app.route('/') def index(): return '<h1>泥豪,世界!</h1>\ <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2700654223,2122220372&fm=26&gp=0.jpg"> \ <img src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=350647292,841711&fm=27&gp=0.jpg"> \ <img src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=4121236200,1201346551&fm=27&gp=0.jpg">' @app.route("/me") def me_api(): return { "username": 'wanghailin', "theme": 'theme', "image": 'image', } @app.route('/json') def exp4(): data = request.args.get('data', 'null') json_dict = { "user_id": 110, "user_name": "kenan", "data": data, } return jsonify(json_dict) @app.route("/index") def test(): return render_template('index.html', username=username) @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id # 状态保持:cookie @app.route('/cookie') def set_cookie(): resp = make_response('this is to set cookie') resp.set_cookie('username', 'scrat', max_age=6) return resp @app.route('/request') def resp_cookie(): resp = request.cookies.get('username') return resp # 状态保持:session @app.route('/index1') def index1(): session['username'] = 'scrat' return redirect(url_for('index2')) @app.route('/index2') def index2(): return session.get('username') # 请求勾子 # 在第一次请求之前调用,可以在此方法内部做一些初始化操作 @app.before_first_request def before_first_request(): print("before_first_request") # 在每一次请求之前调用,这时候已经有请求了,可能在这个方法里面做请求的校验 # 如果请求的校验不成功,可以直接在此方法中进行响应,直接return之后那么就不会执行视图函数 @app.before_request def before_request(): print("before_request") # if 请求不符合条件: # return "laowang" # 在执行完视图函数之后会调用,并且会把视图函数所生成的响应传入,可以在此方法中对响应做最后一步统一的处理 @app.after_request def after_request(response): print("after_request") response.headers["Content-Type"] = "application/json" return response # 请每一次请求之后都会调用,会接受一个参数,参数是服务器出现的错误信息 @app.teardown_request def teardown_request(e): print("teardown_request") if __name__ == "__main__": app.run(host='127.0.0.1', port=8080)