flask学习笔记

  1. 创建flask虚拟环境
    conda create --name gisPy36 python=3.6
    source activate gisPy36
  2. 安装flask,和相关扩展
    pip install flask
    数据库操作,这个是py3的库,配置及相关操作参考flask学习笔记-数据库相关
    pip install PyMySQL
    数据库ORM扩展包
    pip install flask-sqlalchemy
    数据库迁移扩展包
    pip install flask-migrate
    使用bootstrap
    pip install flask-bootstrap

    暂时不使用JWT,因为涉及的知识点太多,花的时间比较多。
    JWT登录验证,这里先使用PyJWT 1.4.0,后面在看看flask-jwt扩展
    pip install PyJWT

jsonify返回一个Response对象,可以用来设置cookie

项目结构:
使用Blueprint来规划。
两点需要注意的地方:

  1. 路由装饰器由Blueprint提供。下面是举例
    @main.app_errorhandler(404)
    def page_not_found(e):
    return render_template('404.html'), 404
  2. url_for的使用略有不同
    默认Blueprint会带有一个命名空间,就是构造函数的第一个参数。如果命名空间是mian,那么index的注册端点是main.index。
    其URL使用url_for(‘main.index’)获取。如果是当前Blueprint可以省略空间名写成url_for(‘.index’)。否则必须带有空间名

g环境变量

需要导入
from flask import g
添加属性并赋值
g.name = 'John'
获取属性
name = g.get('name','no name')
判断属性是否存在
if hasattr(g, 'needLogin'):
...

返回模板和cookie

resp = make_response(render_template("index.html", cls='ShowLoginModal'))
return resp

日志处理

import logging
from logging.handlers import RotatingFileHandler

# 1024*1024*10
handler = RotatingFileHandler('emails.log', encoding='UTF-8',maxBytes=1024*1024*10,backupCount=50)
handler.setLevel(logging.DEBUG)
# logging的级别主要有NOTSET、DEBUG、INFO、WARNING、ERROR和CRITICAL
logging_format = logging.Formatter(
'%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
handler.setFormatter(logging_format)
app.logger.addHandler(handler)

获取当前项目路径

curPath = os.path.split(os.path.realpath(__file__))[0]