# encoding=utf-8 from flask import Flask from flask import g import random app = Flask(__name__) @app.before_request def set_on_g_object(): x = random.randint(0,9) app.logger.debug('before request g.x is {x}'.format(x=x)) g.x = x @app.route("/") def test(): g.x=1000 return str(g.x) @app.after_request def get_on_g_object(response): app.logger.debug('after request g.x is{g.x}'.format(g=g)) return response
二:Flask中靜態文件的處理css
# encoding=utf-8 from flask import Flask from flask import g from flask import send_from_directory from flask import url_for import random app = Flask(__name__) @app.route("/") def test(): return "url建立方式一" def hello(): return "url建立方式二" app.add_url_rule("/index/",endpoint="hello",view_func=hello) @app.route('/url1') def Create_url1(): return url_for('static',filename="style.css") app.add_url_rule('/attachment/<path:filename>',endpoint='attachment',build_only=True) @app.route('/url2') def Create_url2(): return url_for('attachment',filename="upload.txt")
# encoding=utf-8 from flask import Flask from flask import g from flask import send_from_directory from flask import url_for import os.path app = Flask(__name__) dirpath = os.path.join(app.root_path,'upload') @app.route("/download/<path:filename>") def downloader(filename): return send_from_directory(dirpath,filename,as_attachment=True)
# encoding=utf-8 from flask import Flask from flask import g from flask import send_from_directory from flask import url_for import os.path app = Flask(__name__,static_url_path="/test") @app.route("/") def static_create(): return url_for('static',filename='style.css')
五、session 也是一個 request context 的變量,但它把數據保存到了 cookie 中併發送到了客戶端,客戶端再次請求的時候又帶上了cookiepython