Flask 新增資料到 MySQL
本文的參考專案 https://github.com/shinder/flask-practice
承上篇,這裡要使用 Postman POST 傳送 JSON 文件,然後 Flask 接收後寫入資料庫。
Flask route 寫法:
@app.route('/receive-json', methods=['POST'])
def receive_json():
(cursor, cnx) = modules.mysql_connection.get_cursor()
data = json.loads(request.get_data()) # JSON 字串轉換為 dict
p = {}
sids = [] # 用來記錄新增的 primary key
p['name'] = data['name'] if 'name' in data else ''
p['email'] = data['email'] if 'email' in data else ''
p['mobile'] = data['mobile'] if 'mobile' in data else ''
p['birthday'] = data['birthday'] if 'birthday' in data else '1900-01-01'
p['address'] = data['address'] if 'address' in data else ''
# 兩種作法
sql1 = ("INSERT INTO `address_book`"
"(`name`, `email`, `mobile`, `birthday`, `address`, `created_at`"
") VALUES (%s, %s, %s, %s, %s, NOW())")
sql2 = ("INSERT INTO `address_book`"
"(`name`, `email`, `mobile`, `birthday`, `address`, `created_at`"
") VALUES (%(name)s, %(email)s, %(mobile)s, %(birthday)s, %(address)s, NOW())")
cursor.execute(sql1, (p['name'], p['email'], p['mobile'], p['birthday'], p['address']))
sids.append(cursor.lastrowid) # 取得新增項目的 primary key
cursor.execute(sql2, p) # 使用 dict
sids.append(cursor.lastrowid)
cnx.commit() # 提交新增的資料才會生效
return jsonify(sids) # 輸出 JSON 格式
Postman 發需求的網址 http://localhost:5000/receive-json
,JSON 文件如下:
{
"address": "台南市",
"birthday": "2000-11-22",
"email": "wwww@test.com",
"mobile": "0918777-777",
"name": "陳小華"
}
沒有留言:
張貼留言