Flask Web開發入門(九)之(zhī)表單處理
發表時(shí)間:2018-1-10
發布人(rén):融晨科技
浏覽次數:46
本章我們介紹Flask Web開發中的(de)表單處理
application/json類型請求
- 前台請求代碼:
$.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('新增失敗!')
}
}
})
後台捕獲請求,request.data存儲了(le/liǎo)我們的(de)請求數據
後台出(chū)處理代碼,其中參數d爲(wéi / wèi)dict類型數據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類型請求
- 我們稍微修改下前台發送代碼,不(bù)指定contentType參數:即指定請求内容格式。注意:雖然我們的(de)請求數據是(shì)JSON字串,但Ajax中沒有指定contentType參數,那麽數據請求格式仍舊爲(wéi / 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 {
layer.alert('新增失敗!')
}
}
})
通過後台代碼調式,我們可以(yǐ)看到(dào)request.form存儲了(le/liǎo)前台的(de)請求數據如下:
注意上(shàng)圖紅框部分:
request.form是(shì)一個(gè)ImmutableMultiDict類型的(de)對象
request.form的(de)鍵值key存儲了(le/liǎo)請求數據的(de)JSON字串
request.form的(de)長度爲(wéi / wèi)1
因此,通過上(shàng)面的(de)代碼分析,我們定義Flask表單處理後台代碼實現如下,其中參數d是(shì)一個(gè)ImmutableMultiDict類型對象:
# add monitor
def add_monitor(d):
logger.debug('add monitor is %s' % d)
conn = monitor_db.get_connection_with_url(url)
for key in d.keys():
logger.debug("form data is %s" % json.loads(key))
d_dict = json.loads(key)
conn.execute(T_Monitor.insert(), [{
'credit_type': d_dict['credit_type']
, 'query_type': d_dict['query_type']
, 'credit_status': d_dict['credit_status']
, 'elapsed_time': int(random.random() * 100)
}])
實現效果
源碼參考:https://github.com/ypmc/flask-sqlalchemy-web