时间:2021-07-01 10:21:17 帮助过:79人阅读
#!/usr/bin/env python # encoding: utf-8 from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'hello world' if __name__ == '__main__': app.run(debug=True) #app.run(host='127.0.0.1', port=8000)
之后,访问http://localhost:5000
支持post/get提交
@app.route('/', methods=['GET', 'POST'])
多个url指向
@app.route('/') @app.route('/index')
不管post/get使用统一的接收
from flask import request args = request.args if request.method == 'GET' else request.form a = args.get('a', 'default')
处理json请求
request的header中
"Content-Type": "application/json"
处理时:
data = request.get_json(silent=False)
获取post提交中的checkbox
{%for page in pages %}{%endfor%} page_ids = request.form.getlist("do_delete") 使用url中的参数
@app.route('/query//') def query(qid): pass 在request开始结束dosomething
一般可以处理数据库连接等等from flask import g app = ..... @app.before_request def before_request(): g.session = create_session() @app.teardown_request def teardown_request(exception): g.session.close()注册Jinja2模板中使用的过滤器
@app.template_filter('reverse') def reverse_filter(s): return s[::-1]或者
def reverse_filter(s): return s[::-1] app.jinja_env.filters['reverse'] = reverse_filter可以这么用
def a():... def b():... FIL = {'a': a, 'b':b} app.jinja_env.filters.update(FIL)注册Jinja2模板中使用的全局变量
JINJA2_GLOBALS = {'MEDIA_PREFIX': '/media/'} app.jinja_env.globals.update(JINJA2_GLOBALS)定义应用使用的template和static目录
app = Flask(__name__, template_folder=settings.TEMPLATE_FOLDER, static_folder = settings.STATIC_PATH)使用Blueprint
from flask import Blueprint bp_test = Blueprint('test', __name__) #bp_test = Blueprint('test', __name__, url_prefix='/abc') @bp_test.route('/') -------- from xxx import bp_test app = Flask(__name__) app.register_blueprint(bp_test)实例:
bp_video = Blueprint('video', __name__, url_prefix='/kw_news/video') @bp_video.route('/search/category/', methods=['POST', 'GET']) #注意这种情况下Blueprint中url_prefix不能以 '/' 结尾, 否则404使用session
包装cookie实现的,没有session idapp.secret_key = 'PS#yio`%_!((f_or(%)))s'然后
from flask import session session['somekey'] = 1 session.pop('logged_in', None) session.clear() #过期时间,通过cookie实现的 from datetime import timedelta session.permanent = True app.permanent_session_lifetime = timedelta(minutes=5)反向路由
from flask import url_for, render_template @app.route("/") def home(): login_uri = url_for("login", next=url_for("home")) return render_template("home.html", **locals())上传文件