封装flask核心对象
class Application(Flask):
def __init__(self,import_name, template_folder=None,root_path=None):
super( Application,self).__init__(import_name,template_folder=template_folder,root_path=root_path,static_folder=None)
self.config.from_pyfile('config/base_setting.py')
if "ops_config" in os.environ:
self.config.from_pyfile("config/{}_setting.py".format(os.environ['ops_config']))
db.init_app(self)
配置静态资源路径
flask 的静态资源位置默认存放在项目目录下的static目录下,我们可以通过修改static_url_path的参数来修改位置,但这并不是我们想要的,因为我们的静态资源不一定放在当前项目下,甚至不一定放在当前服务器下。所以灵活的flask为我们提供了send_from_directory来配置静态文件的参数
from flask import Blueprint,send_from_directory
from application import app
route_static = Blueprint('static',__name__)
@route_static.route("/<path:filename>")
def index(filename):
app.logger.info(filename)
return send_from_directory(app.root_path+"/web/static/",filename)
配置模板文件路径参数
这个就比较简单了,通过实例化flask核心对象时传参就可以得到。
db = SQLAlchemy()
app = Application(__name__,template_folder=os.getcwd()+"/web/templates/",root_path=os.getcwd())
配置参数的配置
根据项目使用情景不同,我们会在config目录下新建基础参数(base_config.py),开发环境参数(local_config.py),生产环境参数(production_config.py),这个的设置也是在核心对象封装时定义的。
if "ops_config" in os.environ:
self.config.from_pyfile("config/{}_setting.py".format(os.environ['ops_config']))
配置统一登录拦截器
虽然flask框架自带的有flask_login 拦截插件,但是插件在对于权限的作用上不上那么便捷,所以这里所以就统一登录拦截器,该拦截器主要通过效验cookie值进行效验以及拦截,如有大家有对flask_login 更好的封装使用也请不吝分享
包存登录信息
def geneAuthCode(user_info = None ):
m = hashlib.md5()
cookie_str = "%s-%s-%s-%s" % (user_info.uid, user_info.login_name, user_info.login_pwd, user_info.login_salt)
m.update(cookie_str.encode("utf-8"))
return m.hexdigest()
配置无需登录可以访问的页面或者资源
STATIC_LOGIN_URLS = [
"^/static",
"^/favicon.ico"
]
ALLOWED_LOGIN_URLS = [
]
页面拦截器(拦截一些需要用户登录才能访问的页面)
def check_login():
cookies = request.cookies
return_result = False
auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config['AUTH_COOKIE_NAME'] in cookies else None
if auth_cookie:
auth_info = auth_cookie.split("#")
if len(auth_info) ==2:
user_info = User.query.filter_by(uid=auth_info[1]).first()
if user_info:
if auth_info[0] != UserService.geneAuthCode(user_info):
return_result = user_info
return return_result
@app.before_request
def new_before_request():
allowed_login_urls = app.config['ALLOWED_LOGIN_URLS']
static_login_urls = app.config['STATIC_LOGIN_URLS']
path = request.path
# 如果是静态文件就不要查询用户信息了
pattern = re.compile('%s' % "|".join(static_login_urls))
if pattern.match(path):
return
user_info = check_login()
g.current_user = None
if user_info:
g.current_user = user_info
pattern = re.compile('%s' % "|".join(allowed_login_urls))
if pattern.match(path):
return
if not user_info:
return redirect(url_for("web.login"))
return