flask 知识点总结


============================
request对象的常用属性
============================
具体使用方法如下:
request.headers, request.headers.get('If-None-Match')
request.json, request.json['value'] 或 request.json.get('detail_msg', "")
request.args, request.args.get('limit', 10)来获取query parameters
request.form, request.form['username'], 来获取POST/PUT request的form attribute
request.cookies, request.cookies.get('username') 另,response.set_cookie('username', 'the username')
request.method
request.request.path
flash(), 写flash字符串, 模板中可以使用get_flashed_messages()拿到写入的字符串.
   flash() 可以加上catergory参数, 对应的get_flashed_messages()加上category_filter来获取不同的flash字符串.

 
form 元素值的获取示例:
<input name="my_date" type="date" class="form-control" placeholder="date (like 20141231)" required autofocus>

form上元素比如input, 必须设置name属性, 在view python中, request.form['my_date']获取input的值, 这里的my_date是input元素的name, 而不是id属性.
另外,推荐使用 my_date=request.form.get('my_date',''),  而不是直接用my_date=request.form['my_date'], 后者一直取不到值, 直接跑出python 异常.  


   

============================   
request、g 和 session 对象
============================
flask的 flask._app_ctx_stack  和 request、 g、 session 都是 context 对象, 而且都是stack, 都是建在 Werkzeug 的 Thread Local 对象之上的, 可以用threading.local()来理解这样的对象, 针对每个web请求, server端即有一个线程对应, 因为是 thread local 架构, 即保证了线程安全. 这种实现的好处非常明显, 在所有的函数内部, 都可以直接使用这些全局对象, 也可以使用这些对象在不同函数之间传递数据.


应用上下文flask._app_ctx_stack 和 flask.g 差不多, 可以在这两个对象内部保存一些特定的数据, 当然这些数据只在"一个请求"的生命周期中有效. 不过flask._app_ctx_stack 推荐给extension的开发者使用, flask.g 留给web 开发使用. 如果要"跨请求"来共享数据, 需要使用 session 对象.  


在模板内部, 可以使用config, request、g 和 session 对象, 以及 get_flashed_messages()和url_for() 函数。
在视图函数中, 可以使用request、g 和 session 对象
 

 
============================   
视图函数返回值
============================
flask视图函数返回值, 原则上应该是一个response对象, 但也允许有其他类型的返回值, flask会自动将这些类型转成 response 对象, 转换的规则是:
1. 如果返回的是一个response对象, (我们可使用 make_response() 生成 response 对象), 那么flask直接返回它
2. 如果返回的是一个字符串, 将被转换为一个包含作为响应体的字符串、一个 "200 OK" 出错代码、一个 text/html MIME 类型的响应对象
3. 如果返回的是一个元组, 元祖的格式应该是(response,)或 (response, status), 或 (response, headers) 或 (response, status, headers) 形式.  flask 将会自动将status和headers更新到最终的response中.
4。如果以上都不是, 那么 Flask 会假定返回值是一个有效的 WSGI application, 并把它转换为一个响应对象, 比如一个json数据包即为一个有效的WSGI application.



-----------------------------
API视图常用的返回值为
-----------------------------
return jsonify({'item': check_itm_code, 'echo_msg': 'successful'}), 201

-----------------------------
网页视图函数常用的返回值为:
-----------------------------
return render_template('show_entries.html', entries=entries) #缺省status为200, OK
return render_template('page_not_found.html'), 404
return make_response(render_template('index.html', foo=42))



============================
session对象的使用
============================
session['logged_in'] = True #为session设置logged_in flag
session.pop('logged_in', None) #清空session中的logged_in flag



============================
cookies的使用
============================

读取 cookies:
from flask import request
@app.route('/')
def index():
    username = request.cookies.get('username')
    # 使用 cookies.get(key) 来代替 cookies[key] ,
    # 以避免当 cookie 不存在时引发 KeyError
    
储存 cookies:
from flask import make_response
@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp



    

============================
日志
============================
flask 已经为我们准备好了 logger 对象, app.logger 即为该logger对象, 和一般的console程序一样, 我们只需在web启动脚本中, 为root logger设置handler, 无需为flask logger专门再设置handler.  记log直接使用app.logger.info()等方法即可.  

如下代码, 记录出错log
@app.errorhandler(500)
def internal_error(exception): #这里exception是一个对象
    app.logger.exception(exception)
    return render_template('500.html'), 500
    

    

============================
Request的中断和ErrorHandler
============================    
在view函数中, 如果需要中断request, 可以使用abort(500)或者直接raise exception. 当然我们还需要显示一个出错页面给用户看. 所以需要定制一下ErrorHandler,  一般只需要2个handler即可, 一个是404错误, 一个是500一类的服务器端错误.
@app.errorhandler(404)
# 这个handler可以catch住所有的 abort(404) 以及找不到对应router的处理请求
def page_not_found(error):
    target = request.path + "?" + request.query_string
    app.logger.error("404 error for link: "+target)
    # app.logger.exception(error)
    return render_template('404.html', link=target), 404


@app.errorhandler(Exception)
# 这个handler可以catch住所有的 abort(500) 和 raise exeception.
# traceback.html 页面取自 airflow 项目
def show_traceback(error):
    return render_template(
        'traceback.html',
        hostname=socket.gethostname(),
        nukular=ascii_.nukular,
        info=traceback.format_exc()), 500

 
    
    
============================
blueprint
============================    
blueprint视图函数和普通视图函数一样, 可以使用flask.g, flask.request, flask.session, 但使用application级别的对象(比如config和logger),不能直接用app.logger, 必须通过current_app对象, 比如 current_app.logger, current_app.config,  subject=current_app.config['MAIL_SUBJECT']   
 
另外, blueprint 也可以有 before_request, teardown_request, errorhandler 装饰器, 但我觉得一般不必增加blueprint级别装饰函数, 直接共用app的对等函数即可, 除非一定非要将blueprint做成纯粹的 plug&play.

url_for('blueprint123.index')

 

 

 
Blueprint 是组织module的一个很好的方式, 通常我们会为不同的 Blueprint 设置不同的url prefix.
在设置了url prefix后, html 模板中与这个blueprint相关的link 字符串, 都需要加上url prefix, 否则路由地址就不对了.

当然这样的写法其实很是很糟糕的, hard code 的url prefix一多, 哪一天要调整这个url prefix就麻烦了.

最好的作法, 当然不是到处hard code 链接地址了, 推荐使用url_for()函数.  
加了url prefix之后, 使用 url_for() 函数时, 需要为view函数加一个命名空间, 到底这个命名空间取什么,  结论是 Blueprint的名称, 不是Blueprint对象的名称, 也不是python 模块的名称. 这是我花了很长时间才试验出来, 见下面的示例:


#views.py
mod = Blueprint('myReport', __name__, url_prefix='/reports')  #Blueprint的名称是 myReport


@mod.route("/csv_data/<report_name>/<time_id>")
def download_csv_view(report_name, time_id):
    return 'a,b,c,d,e'

    
def redirect_sample():
    return redirect(url_for('myReport.download_csv', report_name='report_1', time_id='201406' ))
    
 
模板上的写法也是一样,   
 <a href="{{ url_for('myReport.download_csv', report_name='report_1', time_id='201406')}}">
    download csv of report_1(201406)  
</a>

 

 

 

============================
flask 内建的renderer,
============================    
mine_types{'json_renderer':('application/json',),
           'xml_renderer':('application/xml','text/xml','application/x-xml',)
          }
          
除了内建的json和xml两个renderer外, 使用 flask-mimerender 扩展, 可以很容易增加其他的renderer, 比如excel和csv输出.
 

 
============================    
关闭模板中的转义
============================   
方法1, 在Python文件中进行转义, 先在 Markup 对象中进行转义,然后将它传送给模版。一般推荐使用这个方式。
from flask import Markup
result=Markup(result(params))
return render_template('xxx.html', result=result)

方法2, 在模版文件中进行转义. 通过 |safe 过滤器来表示字符串是安全的({{result|safe}})
渲染的时候 {{ result|safe }}

方法3, 暂时禁用全局的自动转义功能。
{% autoescaping false %}
<p>autoescaping is disableed here
<p>{{ will_not_be_escaped }}
{% endautoescape %}

 
 

知识点:
1. API 的url最好包含/api/v1.0 这样的字符串, 加上版本号, 有利于版本控制.
2. api函数的app.route装饰器, methods参数要么缺省, 要么POST/GET都要加, 如果只加一个, request会报HTTP Error 405, METHOD NOT ALLOWED
3. api函数返回类型最好都是json格式, 推荐使用flask的jsonify()作为返回值, 它可以将dict转成json
4. api的消费端, 发起POST请求, 可使用标准库urllib2.Request()方法, 需要指定data和headers参数, 这样才是POST.
如, urllib2.Request(url, data=data_json, headers={'Content-Type': 'application/json'})
5. api的消费端, 发起POST请求, 往往需要传json数据进去, 可使用json库的json.dumps()将dict转成json.
6. api的消费端得到的response, 其类型是str, 可使用json库的json.loads() 转成json格式



@app.route('/user/<username>')
@app.route('/user/<converter:variable_name> ')
flask内建的converter可以有:
@app.route('/user/<int:user_id> ')
@app.route('/user/<float:salary> ')
@app.route('/user/<path:full_dept> ')

如果有one和two都是可选参数, 就不能使用myapp/api/getDetails/<one>/<two>形式的url了, 推荐使用?和kv结合的形式.
比如: http://localhost:5003/myapp/api/getDetails?one=abc&two=123&three=xxx

@mod.route("/myapp/api/getDetails", methods=('GET', 'POST'))             
def getPrStatusDetail():
    one=request.args.get('one', '')
    two=request.args.get('two', '')
    three=request.args.get('three', '')
    grid_data=SomeObject.getDetail(one,two,three)
    return JsonConverter.ObjListToJson(grid_data),201  



API 模块
@mod.route("/api/v1.0/test/simple", methods=('POST','GET'))

def test_simple_view():
    return jsonify({'request.method': request.method, 'echo_msg': 'successful' } ), 201   


测试代码    
#request for test/simple, method is GET
import json
import urllib2
url = "http://localhost:5000/api/v1.0/test/simple"
req = urllib2.Request(url)
f = urllib2.urlopen(req)
httpCodes=f.getcode()
responseStr = f.read()
f.close()
json_data=json.loads(responseStr)
echo_msg=json_data['echo_msg']




--------------------------------------------------------
API 模块
url有一个动态参数, 没有指定类型, 则表示为str型
@mod.route("/api/v1.0/test/str_arg/<check_itm_code>", methods=('POST','GET'))
def test_str_argument_view(check_itm_code):
    return jsonify({'request.method': request.method,'item': check_itm_code, 'echo_msg': 'successful'}), 201
    
    
测试代码  
#request for test/str_arg/<check_itm_code>, method is GET
import json
import urllib2
url = "http://localhost:5000/api/v1.0/test/str_arg/abc"
req = urllib2.Request(url)
f = urllib2.urlopen(req)
httpCodes=f.getcode()
responseStr = f.read()
f.close()
json_data=json.loads(responseStr)
echo_msg=json_data['echo_msg']





--------------------------------------------------------
API 模块
url有一个动态参数, 指定为int型, 还可以指定成float型
@mod.route("/api/v1.0/test/int_arg/<int:seq_no>", methods=('POST','GET'))
def test_int_argument_view(seq_no):
    return jsonify({'request.method': request.method,'seq_no': seq_no, 'echo_msg': 'successful'}), 201  
    
    
测试代码     
#request for test/int_arg/<int:seq_no>, method is GET
import json
import urllib2
url = "http://localhost:5000/api/v1.0/test/int_arg/123"
req = urllib2.Request(url)
f = urllib2.urlopen(req)
httpCodes=f.getcode()
responseStr = f.read()
f.close()
json_data=json.loads(responseStr)
echo_msg=json_data['echo_msg']


 


除了str/int/float这样常用的url参数, 还支持regex, 比如app.route('/regex("[w]*[Ss]"):collection')


--------------------------------------------------------
API 模块
接受request 包含json格式的数据
@mod.route("/api/v1.0/test/json_post/<check_itm_code>", methods=('POST','GET'))
def test_json_post_view(check_itm_code):
    if not request.json:
        abort(400)  # bad request    
        
    if not 'value' in request.json:
            abort(400)  # bad request    
                 
    value=request.json['value']     
    detail_msg=request.json.get('detail_msg', "")  # if detail_msg is not set, use empty  
    return jsonify({'request.method': request.method,'value': value,'detail_msg':detail_msg, 'echo_msg': 'successful'}), 201    
            
            
    
测试代码
#request for test/json_post/<check_itm_code>, method is POST
#需要在urllib2.Request()中指定data和headers参数, 这样才是POST
import json
import urllib2
data = {'value': '100',
        'detail_msg': 'SOMETHING HERE'
}
data_json = json.dumps(data)
url = "http://localhost:5000/api/v1.0/test/json_post/hang_check"
req = urllib2.Request(url, data=data_json, headers={'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
httpCodes=f.getcode()
responseStr = f.read()
f.close()
json_data=json.loads(responseStr)
echo_msg=json_data['echo_msg']

 


 

=====================================================
WTF 相关
=====================================================

WTF 常用的 field 类型
'BooleanField', 'TextAreaField', 'PasswordField', 'FileField',
'HiddenField', 'SubmitField', 'TextField'


常用的验证方式有:
'DataRequired', 'data_required', 'Email', 'email', 'EqualTo', 'equal_to',
'IPAddress', 'ip_address', 'InputRequired', 'input_required', 'Length',
'length', 'NumberRange', 'number_range', 'Optional', 'optional',
'Required', 'required', 'Regexp', 'regexp', 'URL', 'url', 'AnyOf',
'any_of', 'NoneOf', 'none_of', 'MacAddress', 'mac_address', 'UUID'


=====================================================
jinja2 相关
=====================================================

使用 {# ... #}注释代码
使用 {% set var='' %} 进行赋值,  {% set key, value = call_something() %}
使用 {{…}} 调用变量
使用 {% if … %},{% elif otherthing %} ,{% else %},{% endif %} 控制流程
使用 {% for … in … %},{% endfor %} 定义循环
使用 {% block …%},{% endblock %} 定义继承内容块
使用 {% extends “FILENAME” %},{% block …%},{% endblock %} 引入模版继承的内容

原文地址:https://www.cnblogs.com/harrychinese/p/flask_tips.html