您當前位置>首頁 » 新聞資訊 » 網站(zhàn)建設 >
Flask Web開(kāi)發入門(mén)(九)之表單處理(l≥↑>ǐ)
發表時(shí)間(jiān):2018-1-10
發布人(rén):葵宇科(kē)技(jì)
浏覽次數(shù):48
本章(zhāng)我們介紹Flask Web開(kāε i)發中的(de)表單處理(lǐ)
application/json類型請(qǐng)求
- 前台請(qǐng)求代碼:
$.ajax({
url: '/add'
, type: 'POST'
, data: JSON.stringify(data.field)
,β≈ contentType: 'application/json'
, success: function (response) {
console.log(response);
if (response.code == 0) {
layer.msg('新增成功!');
} else {
layer.alert('新增失敗!')
}
₩×↔ }
γ₩ })
後台捕獲請(qǐng)求,request.data存儲了(le)我們的(de)請(qǐng)求數(shù)據
後台出處理(lǐ)代碼,其中參數(shù)d為(wèi)dict類型數(shù)據request.data
def add_monitor(d):
logger.debug('add monitor is %s' % d)
d = json.loads(d)
conn = αφ monitor_db.get_connection_with_url(url)≠
# Content-Type: application/json
conn.execute(T_Monitor.insert(), <✘[{
'credit_type': d['credit_type']
, 'query_type': d['query_type']
, 'credit_status': d['credit_status']
, 'elapsed_time': int(random.random() * 100)
}])
application/x-www-form-urlencoded類型請(qǐng)求
- 我們稍微(wēi)修改下(xià)前台發送代碼,不(bù)指定contentType參數(shù):即指定請(qǐng)求內(nèi)容格式。注意:雖然我&•們的(de)請(qǐng)求數(shù)據是(shì)JSONγδ字串,但(dàn)Ajax中沒有(yǒu Ω↑)指定contentType參數(shù),那(nà)麽數(shù)據請(qǐng)求格式仍舊£σ×€(jiù)為(wèi)application/x-www-form-urlencoded
$.ajax({
url: '/add'
, type: 'POST'
, data: JSON.stringify(data.field)
↑¥ , success: function (response) {
console.log(response);
if (response.code == 0) {
layer.msgδ "×('新增成功!');
} else {
la®∞yer.alert('新增失敗!')
}
↓& }
})
通(tōng)過後台代碼調式,我們可(∏≈kě)以看(kàn)到(dào)request.form存儲了(le)前台的(de)請(qǐng)求數(shù÷±)據如(rú)下(xià):
注意上(shàng)圖紅(hóng)框部分(fēn):
request.form是(shì)一(yī)個(gè)ImmutableMultiDict類型的(de)對≤∑→<(duì)象
request.form的(de)鍵值key存儲了(le)請(qǐng)求數(shù)據的(de)φ∞JSON字串
request.form的(de)長(cháng)度為(wèi)1
因此,通(tōng)過上(shàng)面的(de) ♥≤代碼分(fēn)析,我們定義Flask表單處理(lǐ)後台代碼實現( ♣♣xiàn)如(rú)下(xià),其中參↕↓€α數(shù)d是(shì)一(yī)個(gè)ImmutableMultiDicγ♥∑t類型對(duì)象:
# add monitor
def add_monitor(d):
logger.debug('add monitor is %s' % d)
conn = monitor_db.get_connection_wit©≤h_url(url)
for key in d.keys():
logger.debug("form data is %s" % json.loads(key))
d_dict = json.l₩'oads(key)
conn.execute(T_Monitor.ins✘€ert(), [{
'credit_type': d_dict['credit_type']
, 'query_type': d_dict['query_type']
, 'credit_status': d_dict['credit_status']
, 'elapsed_time': int(random.random() * 100)
}])
實現(xiàn)效果
源碼參考:https://github.com/ypmc/f& lask-sqlalchemy-web