后端采用Flask提供几个Restfull风格的API,前端放弃惯用的flasky常用的Jinja模板引擎,采用灵活的Vue.js框架,顺便实践一把前后端分离。既然前后端分离,那么就需要在开发环境独立创建两个项目。下面逐一介绍。
安装node.js
安装vue,安装webpack,安装vue-cli,创建工程
vue是以组件为单位组织成复杂的页面。我们直接在componets下的HelloWorld.vue上进行代码调整和编写。template部分主要包含一个select元素,value对应后端API,触发button会向选择的后端API发送请求。script部分methods部分实现对元素事件的响应,通过axios与后端服务器进行通信,分别采用get和post方法。具体代码如下图:
<template>
<div class="hello">
<button @click="test">测试</button>
<select v-model="selected" name="url-option">
<option value="">选择一个Url</option>
<option value="/api/speech/event_extraction">思必驰警情信息抽取</option>
<option value="/api/speech/addr_fix">思必驰地址理解</option>
<option value="/api/gaode/get_poi">高德关键字搜索</option>
</select>
<input v-model="input_query" style="width: 400px">
<button @click="sendRequest">发送请求</button>
<br></br>
<textarea style="width: 600px; height: 300px">{{ resp }}</textarea>
</div>
</template>
<script>
import axios from 'axios'
// 后端服务器地址
axios.defaults.baseURL = 'http://10.67.*.*:5000';
export default {
name: 'HelloWorld',
data () {
return {
selected: '',
input_query: '',
resp: ''
}
},
methods: {
test () {
axios
.get('/api/hello')
.then(response => {
console.log(response.data.name)
this.resp = response.data.name
})
.cache(error => {
console.error(error)
})
},
sendRequest () {
console.log(this.selected)
axios
.post(this.selected, {query: this.input_query})
.then(response => {
console.log(response)
this.resp = response.data
}).catch(error => {
console.error(error)
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
在vue中还用
v-for 来在前端页面中做for循环,v-on:click=点击,v-if=表示IF语句
后端
打开pycharm,新建一个flask项目
在app.py里编写几个Restfull 风格的API,用于响应前端请求
from flask import Flask, jsonify, request
from flask_cors import CORS
import requests
import json
app = Flask(__name__)
# 实现跨域访问
cors = CORS(app, resources={r"*": {"origins": "*"}})
# get请求
@app.route('/api/hello')
def hello_world():
content = {
"name": "网站",
"num": 3,
"sites": [{"name": "Google", "info": ["Android", "Google 搜索", "Google 翻译"]},
{"name": "Runoob", "info": ["菜鸟教程", "菜鸟工具", "菜鸟微信"]},
{"name": "Taobao", "info": ["淘宝", "网购"]}],
}
return jsonify(content)
# post请求
@app.route('/api/gaode/get_poi', methods=['POST'])
def get_poi():
json_data = request.get_json()
url_prefix = "***"
url = url_prefix + '&keywords=' + json_data['query']
headers = {"Content-Type": "application/json"}
resp = requests.get(url, headers=headers)
text = resp.json()
return text
# 其它接口此处可进行补充.............
if __name__ == '__main__':
app.run(
# TODO 设置无效,原因未知
# host='10.67.*.*',
# port='5000',
# debug=True
)