Vue and Flask achieve front-end and back-end separation

introduction

Recently, I learned about Vue.js, a popular front-end framework. As a new skill, only after practicing and using it can I have a more intuitive experience. Therefore, consider writing a small demo to practice hands-on. The backend uses Flask to provide several Restfull style APIs. The frontend abandons the usual Flasky commonly used Jinja template engine, adopts the flexible Vue.js framework, and practices a front-end separation by the way.
Since the front and back ends are separated, two projects need to be created independently in the development environment. The following are introduced one by one.

front end

Environmental preparation

The development is carried out on the windows10 system.

  1. Install node.js
  2. node.js comes with npm, change the source
npm install  -g cnpm --registry=https://registry.npm.taobao.org
  1. install vue
cnpm install -g vue
  1. Install webpack
cnpm install -g webpack
  1. Install vue-cli
cnpm install -g vue-cli
  1. create project
vue init webpack example
  1. Install project dependencies
cnpm install
  1. Start the project
    Method 1: command start
cnpm run dev

Method 2: Open the project in pycharm and start it.
After the project starts, you will be prompted to enter localhost:8080, and the page can be opened normally in the browser. At this point, the development environment is ready, and the front-end code can be developed below.

code development

The project directory structure is as follows:
Vue project directory
Vue is organized into complex pages in units of components. We directly adjust and write code on HelloWorld.vue under components.
The template part mainly includes a select element, the value corresponds to the backend API, and triggering the button will send a request to the selected backend API.
The methods part of the script part implements the response to element events, communicates with the back-end server through axios, and adopts get and post methods respectively. The specific code is as follows:

<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>

The interface is very simple, as shown below:
insert image description here

rear end

Open pycharm, create a new flask project, and configure venv. The flask project directory is as follows:
insert image description here

Write several Restfull-style APIs in app.py to respond to front-end requests.

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
    )

Click Run. Or start with the command: python -m flask run

Encounter problems

1. In order to support external network access, the backend setting host in app.run does not take effect. It is configured in pycharm, but it can take effect when running. The cause is unknown.
2. Flask cross-domain access

from flask_cors import CORS
cors = CORS(app, resources={
    
    r"*": {
    
    "origins": "*"}})

summary

Flask is a lightweight web back-end framework, and Vue is a front-end framework with good dynamic response performance and convenient development. Using both as the front-end and back-end can quickly build a web application. This article can be used as a reference.

Guess you like

Origin blog.csdn.net/jane_xing/article/details/108602456