一个酷酷的flask应用。
主要用到蓝图.
# -*- coding: utf-8 -*- from flask import Flask,flash,request,render_template,jsonify,session,redirect,url_for,send_from_directory import logging #建立【logger】 logger = logging.getLogger("app_log") #logger.setLevel(log_level) #建立【格式串】 fmter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') #建立【文件句柄】并分别设置级别 hdlr = logging.FileHandler("/home/app/logs/daily.log") #filehandler.setLevel(logging.ERROR) #【文件句柄】和【流句柄】使用【格式串】 hdlr.setFormatter(fmt=fmter) #【logger】连接【句柄】 logger.addHandler(hdlr=hdlr) logger.setLevel(logging.INFO) logger.critical('app has been restarted') app = Flask(__name__) app.secret_key='\xf1\x92Y\xdf\x8ejY\x04\x96\xb4V\x88\xfb\xfc\xb5\x18F\xa3\xee\xb9\xb9t\x04\xf0\x96' app. config['SECRET_KEY'] = 'what_does_app_major_in' app.config.from_object(__name__)
#**********************************蓝图注册********************************#
app.register_blueprint(detail.api)
#**********************************蓝图注册_end********************************#
b
1 @app.before_request 2 def before_request(): 3 session.permanent = True 4 app.permanent_session_lifetime = timedelta(days=30) 5 url_after = request.environ['PATH_INFO'] 6 allow_list = ['login','static','api'] 7 path_list = filter(lambda x: x in url_after,allow_list) 8 if not path_list: 9 if 'username' not in session or session['username'] == '': 10 return redirect(url_for('login')) 11 else: 12 loginname = "admin" 13 ip_dizhi = request.remote_addr 14 #记录登录信息 15 logger.info("User's name is %s,ip is %s,visit %s" % (loginname,ip_dizhi,url_after))
c
@app.errorhandler(404) def page_not_found(error): logger.error('page not find') return render_template('page_not_found.html'), 404
d
@app.route('/', methods=['GET', 'POST']) def jump2summary(): return redirect(url_for('summary')) @app.route("/login",methods=["POST","GET"]) def login(): if request.method=='POST': post_usr=request.form['username'] post_psd=request.form['password'] if not os.path.isfile(pwd_filename): os.mknod(pwd_filename) with open(pwd_filename, 'w') as f: new_pwd = protected('admin') f.write(new_pwd) with open(pwd_filename, 'r') as f: tmp_pwd = f.read() if post_usr == 'admin' and protected(post_psd) == tmp_pwd: session['username'] = post_usr session['password'] = post_psd logger.fatal('success login in') return redirect(url_for('summary')) else: return "(账号密码错误)" return render_template('login.html')