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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/376987.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/376987.shtml
英文地址,請注明出處:http://en.pswp.cn/news/376987.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Postgresql中的hybrid hash join(無狀態機講解)

hybrid hash join hybrid hash join是基于grace hash join 的優化。 在postgresql中的grace hash join 是這樣做的&#xff1a;inner table太大不能一次性全部放到內存中&#xff0c;pg會把inner table 和outer table按照join的key分成多個分區&#xff0c;每個分區(有一個inn…

末日中的黎明

哈哈&#xff0c; 今天是2012-12-21&#xff0c;傳說中的世界末日&#xff0c;不過現在看來&#xff0c;一切都是空的。。。 在這個容易記憶的日子里&#xff0c;我的博客開通了。他將伴隨我以后的學習開發&#xff0c;期望我能充分利用博客&#xff0c;幫我養成常總結、常記筆…

使用numpy.tanh()打印矢量/矩陣元素的雙曲正切值 使用Python的線性代數

Prerequisite: 先決條件&#xff1a; Defining a Vector 定義向量 Defining a Matrix 定義矩陣 Numpy is the library of function that helps to construct or manipulate matrices and vectors. The function numpy.tanh(x) is a function used for generating a matrix / v…

Mahout kmeans聚類

Mahout K-means聚類 一、Kmeans 聚類原理 K-means算法是最為經典的基于劃分的聚類方法&#xff0c;是十大經典數據挖掘算法之一。K-means算法的基本思想是&#xff1a;以空間中k個點為中心進行聚類&#xff0c;對最靠近他們的對象歸類。通過迭代的方法&#xff0c;逐次更新各聚…

Web項目中獲取SpringBean——在非Spring組件中獲取SpringBean

最近在做項目的時候我發現一個問題&#xff1a;Spring的IOC容器不能在Web中被引用(或者說不能被任意地引用)。我們在配置文件中讓Spring自動裝配&#xff0c;但并沒有留住ApplicationContext的實例。我們如果希望在我們的項目中任何位置都能拿到同一個ApplicationContext來獲取…

postgresql對于HashJoin算法的Data skew優化與MCV處理

Data skew 很好理解&#xff0c;即數據傾斜。現實中的數據很多都不是正態分布的&#xff0c;譬如城市人口&#xff0c;東部沿海一個市的人口與西部地區一個市地區的人口相比&#xff0c;東部城市人口會多好幾倍。 postgresql的skew的優化核心思想是"避免磁盤IO"。 優…

JavaScript | 創建對象并通過JavaScript函數在表中顯示其內容

In this example, we created an object named employee with id, name, gender, city, and salary and assigned and displaying the values in the table using JavaScript function. 在此示例中&#xff0c;我們創建了一個名為employee的對象&#xff0c;其對象為id &#x…

基于socket的簡單文件傳輸系統

【實驗目的及要求】 在 Uinx/Linux/Windows 環境下通過 socket 方式實現一個基于 Client/Server 文件傳輸程序。 【實驗原理和步驟】 1. 確定傳輸模式:通過 socket 方式實現一個基于 Client/Server 或 P2P 模式的文件傳輸程序。 2. 如果選擇的是 Client/Server 模式的文件傳輸…

《GPU高性能編程-CUDA實戰》中例子頭文件使用

《GPU高性能編程-CUDA實戰&#xff08;CUDA By Example&#xff09;》中例子中使用的一些頭文件是CUDA中和C中本身沒有的&#xff0c;需要先下載這本書的源碼&#xff0c;可以在&#xff1a;https://developer.nvidia.com/content/cuda-example-introduction-general-purpose-g…

mcq 隊列_人工智能| AI解決問題| 才能問題解答(MCQ)| 套裝1

mcq 隊列1) Which of the following definitions correctly defines the State-space in an AI system? A state space can be defined as the collection of all the problem statesA state space is a state which exists in environment which is in outer spaceA state sp…

Postgresql的HashJoin狀態機流程圖整理

狀態機 可以放大觀看。 HashJoinState Hash Join運行期狀態結構體 typedef struct HashJoinState {JoinState js; /* 基類;its first field is NodeTag */ExprState *hashclauses;//hash連接條件List *hj_OuterHashKeys; /* 外表條件鏈表;list of …

Ajax和Jsonp實踐

之前一直使用jQuery的ajax方法&#xff0c;導致自己對瀏覽器原生的XMLHttpRequest對象不是很熟悉&#xff0c;于是決定自己寫下&#xff0c;以下是個人寫的deom&#xff0c;發表一下&#xff0c;聊表紀念。 Ajax 和 jsonp 的javascript 實現&#xff1a; /*! * ajax.js * …

得到前i-1個數中比A[i]小的最大值,使用set,然后二分查找

題目 有一個長度為 n 的序列 A&#xff0c;A[i] 表示序列中第 i 個數(1<i<n)。她定義序列中第 i 個數的 prev[i] 值 為前 i-1 個數中比 A[i] 小的最大的值&#xff0c;即滿足 1<j<i 且 A[j]<A[i] 中最大的 A[j]&#xff0c;若不存在這樣的數&#xff0c;則 pre…

學習語言貴在堅持

學習語言貴在堅持 轉自&#xff1a;http://zhidao.baidu.com/link?urlr2W_TfnRwipvCDLrhZkATQxdrfghXFpZhkLxqH1oUapLOr8jXW4tScbyOKRLEPVGCx0dUfIr-30n9XV75pWYfK給大家介紹幾本書和別處COPY來的學習C50個觀點 《Thinking In C》&#xff1a;《C編程思想》&#xff1b; 《The…

stl vector 函數_在C ++ STL中使用vector :: begin()和vector :: end()函數打印矢量的所有元素...

stl vector 函數打印向量的所有元素 (Printing all elements of a vector) To print all elements of a vector, we can use two functions 1) vector::begin() and vector::end() functions. 要打印矢量的所有元素&#xff0c;我們可以使用兩個函數&#xff1a;1) vector :: b…

JqueryUI入門

Jquery UI 是一套開源免費的、基于Jquery的插件&#xff0c;在這里記錄下Jquery UI 的初步使用。 第一、下載安裝 下載Jquery,官網&#xff1a;http://jquery.com;  下載Jquery UI&#xff0c;官網&#xff1a;http://jqueryui.com/ Jquery的部署就不說了&#xff0c;說下Jqu…

gp的分布、分區策略(概述)

對于大規模并行處理數據庫來說&#xff0c;一般由單master與多segment組成。 那么數據表的單行會被分配到一個或多個segment上&#xff0c;此時需要想一想分布策略 分布 在gp6中&#xff0c;共有三個策略&#xff1a; 哈希分布 隨機分布 復制分布 哈希分布 就是對分布鍵進行…

[ Java4Android ] Java基本概念

視頻來自&#xff1a;http://www.marschen.com/ 1.什么是環境變量 2.JDK里面有些什么&#xff1f; 3.什么是JRE&#xff1f; 什么是環境變量&#xff1f; 1.環境變量通常是指在操作系統當中&#xff0c;用來指定操作系統運行時需要的一些參數; 2.環境變量通常為一系列的鍵值對&…

_thread_in_vm_Java Thread類的靜態void sleep(long time_in_ms,int time_in_ns)方法,帶示例

_thread_in_vm線程類靜態無效睡眠(long time_in_ms&#xff0c;int time_in_ns) (Thread Class static void sleep(long time_in_ms, int time_in_ns)) This method is available in package java.lang.Thread.sleep(long time_in_ms, int time_in_ns). 軟件包java.lang.Thread…

大規模web服務開發技術(轉)

前段時間趁空把《大規模web服務開發技術》這本書看完了&#xff0c;今天用一下午時間重新翻了一遍&#xff0c;把其中的要點記了下來&#xff0c;權當復習和備忘。由于自己對數據壓縮、全文檢索等還算比較熟&#xff0c;所以筆記內容主要涉及前5章內容&#xff0c;后面的零星記…