取后端数据_用 Flask+Axios 实现前后端数据通信:查询动森鱼类价格
對于數據分析/挖掘工程師,能把自己的數據分析or建模結果做成前后端兼備的 demo 是個比較有用的技能,這里介紹一種比較簡單的實現方式,無需數據庫,用 Flask 啟動后端,依賴 Axios 實現前后端數據的互動。
工具準備
Flask
pip install flaskAxios
https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js數據
下面的例子用動物森友會中魚類的價格、活動季節、圖片等數據作為測試數據,通過關鍵詞進行查詢并做前端展示,數據來源:
https://raw.githubusercontent.com/chendaniely/animal_crossing/master/data/final/without_raw_html/acnh_fish_n.tsv下面介紹實現前后端分離的過程:前端輸入魚的名稱,點擊前端“查詢”按鈕,通過 Axios 把前端輸入的字符串傳給后端的函數,函數通過魚的名稱進行檢索,找出該魚類的價格及圖片鏈接,數據查詢完成后,把結果傳給前端進行可視化。
后端
首先是后端部分,創建一個 main.py 文件作為我們的后端主文件,首先引入相關包,創建一個 Flask 實例:
import pandas as pd from flask import Flask, jsonify, request from flask_cors import CORS import traceback ? app = Flask(__name__) app.config.from_object(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1 ? CORS(app, resources={r'/*': {'origins': '*'}})然后寫處理數據的函數,將結果以 dict 形式存儲:
# 數據處理 def get_data_by_keyword(keyword):df = pd.read_csv(base_url + 'animal-crossing-fish-info.csv')df['price'] = df['price'].astype(str)price = df[df['name'] == keyword]['price'].iloc[0]image = df[df['name'] == keyword]['image'].iloc[0].split('t')[0] + '>'fish_info = {'price': str(price), 'image': image}return {'fish_info': fish_info}接下來是接收前端輸入數據的部分,這里的 /data_generate 即為前端數據進行 post 的目的路徑,通過 request 拿到前端出來的數據后,調用剛才寫好的 get_data_by_keyword() 進行數據處理:
@app.route('/data_generate', methods=['POST']) def data_generate():global dataif request.method == 'POST':try:post_data = request.get_json()keyword = post_data.get('search')data = get_data_by_keyword(keyword)message = {'status': 'success'}except Exception as e:traceback.print_exc()return jsonify({'status': 'fail'})else:return jsonify(message)然后是將上一步處理好的結果數據傳回前端,這里的 /get_data 為前端結果頁面拿數據的路徑:
@app.route('/get_data', methods=['GET']) def get_data():global dataif request.method == 'GET':try:arg = request.args.get('name')response_data = data.get(arg)return jsonify(response_data)except Exception as e:traceback.print_exc()return None最后一步就是啟動 Flask 服務了(端口可自行設置):
if __name__ == '__main__':app.run(port=8000)前端
前端給后端發送數據
后端完成后,就可以寫前端頁面了,首先建一個可輸入關鍵詞查詢的首頁 index.html,先寫好靜態部分,對后面需要操作的組件進行 id 的設置,以便后續調用。這里對 button 組件進行了 onclick 事件的設置,命名 jump(),這樣我們在前端點擊這個 button 時,就會觸發 jump() 事件中的動作:
<body> <div class="container" id="app"><h3 style="text-align:center">動物森友會魚類價格查詢</h3> ?<div style="text-align:center"><input id="search-word" type="text" οnkeydοwn="jump(event);" placeholder=""><button class="btn btn-search" id="click-search" type="button" value="start"onclick="jump()">搜  索</button> ?</div> ? </div> ? </body> </html>拖到瀏覽器中可以直接看到建好的組件了:
然后就要寫用來發送和接收數據的 JavaScript 代碼了!先把需要的 js 文件下載到本地,在 script 腳本頭部調用,下面寫將前端輸入數據發送給后端的代碼,也就是前面在 button 中設置的事件 jump()。這里的 "search-word" 即為輸入框組件的 id,通過 document.getElementById() 取出輸入框中傳入的字符串,通過 Axios 發送給后端:
<script> function jump(){var search_keyword=document.getElementById("search-word").value;axios.post('http://127.0.0.1:8000/data_generate', {search: search_keyword}).then(function (response) {var status = response.data.status;alert(status)if (status == 'success') {window.location.href = 'result.html'} else {alert("Error!")}}).catch(function (error) {alert("Error!");}); } ? </script>前端拿后端發來的數據
上面兩步完成了“前端給后端發送數據”和“后端對前端傳來的數據進行處理”兩個步驟,接下來就是最后一步:前端取后端傳來的數據處理結果,并進行展示。
再建一個 result.html 文件,靜態部分創建兩個 div,分別用來展示圖片和價格:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>動物森友會魚類價格查詢</title><link href="assets/css/mystyle.css" rel="stylesheet"/> </head> <body> ? <div id="fish-image"> ? </div> ? <div id="fish-price"> ? </div> ? ? </body> </html>接下來就是 script 部分,這里通過比較粗暴的 document.getElementById('').innerHTML 方式寫入了,也可以通過其他各種方式或插件用來展示數據:
<script src="assets/js/jquery-3.1.1.min.js"></script> <script src="assets/js/axios.min.js"></script><script> $(document).ready(function(){var price_info;axios.get('http://127.0.0.1:8000/get_data?name=fish_info').then(function (response) {price_info=response.data.price;image=response.data.imagedocument.getElementById('fish-image').innerHTML = imagedocument.getElementById('fish-price').innerHTML = "<p>價格:" + price_info + "鈴錢</p>"}).catch(function (error) {console.log(error);}); }); </script>至此,這個小例子就全部完成了,執行以下命令開啟 Flask 服務:
python main.py然后在本地瀏覽器打開 index.html,如輸入關鍵詞「Frog」進行查詢,得到結果如下:
這個例子僅用來拋磚引玉,大家可以用 HighCharts、AntV 等圖表庫進行形式更多元的數據可視化展示。
完整代碼可移步 Github:
https://github.com/cyansoul/flask-axios-example?github.com第一時間圍觀更多關于數據挖掘的有趣內容,歡迎大家關注公眾號「數據池塘」:
總結
以上是生活随笔為你收集整理的取后端数据_用 Flask+Axios 实现前后端数据通信:查询动森鱼类价格的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: phpcms 指定id范围 调用_Ela
- 下一篇: 账号类型_3-2-3节 文字创作类之账号