当前位置:   article > 正文

flask+vue实现简单的Web应用_vue flask

vue flask

简介

flask是python在web开发上的一个比较轻量的开发框架,vue是前端视图库,是一个MVVM框架。flask+vue可以实现快速的现代web应用开发,这里我们以简单的读写配置文件为例,做一个示例。

项目用到的开发基座有:

  • python 3.8.8
  • flask 1.1.2
  • flask-cors 3.0.10
  • vue 2.6.12
  • vue-cli 4.5.13
  • element-ui 2.15.2

项目目录结构:
目录结构

后端搭建

我们在目录server中,使用flask框架,来提供接口,一个用来读配置文件cc.cfg,一个用来写配置文件cc.cfg:
app.py

from flask import Flask, json, request
from flask_cors import CORS
import json
import configparser
import os

# configuration
DEBUG = True

# instance the app
app = Flask(__name__)
app.config.from_object(__name__)

# enable CORS
CORS(app, resource={r'/*': {'origins': '*'}})


# sanity check route
@app.route('/open', methods=['get'])
def get_info():
    cp = configparser.ConfigParser()
    cur_path = os.getcwd()
    cp.read(cur_path + '/server/cc.cfg')
    sections = cp.sections()
    response = {
        'code': 0,
        'data': {}
    }
    if len(sections) == 0:
        raise Exception('文件不存在或无内容')
    for section in sections:
        response['data'][section] = {}
        for key in cp[section]:
            response['data'][section][key] = cp.get(section, key)

    return json.dumps(response, ensure_ascii=False)


@app.route('/open', methods=['post'])
def set_info():
    req = json.loads(request.data)
    cp = configparser.ConfigParser()
    cur_path = os.getcwd()
    with open(cur_path + '/server/cc.cfg', 'w', encoding='utf-8') as cfg_file:
        for section in req:
            cp.add_section(section)
            for key in req[section]:
                cp.set(section, key, req[section][key])
        cp.write(cfg_file)

    response = {
        'code': 0,
        'data': req
    }
    return json.dumps(response)


if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    app.run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

开启服务:

python .\server\app.py
  • 1

正常启动显示:

 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with windowsapi reloader
 * Debugger is active!
 * Debugger PIN: 136-969-898
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Detected change in 'C:\\Users\\Administrator\\anaconda3\\Scripts\\spyder-script.py', reloading
 * Restarting with windowsapi reloader
 * Debugger is active!
 * Debugger PIN: 136-969-898
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

前端搭建

我们直接使用vue的脚手架vue-cli,在主项目目录控制台执行:

vue create client
  • 1

然后添加相关webpack插件和组件库,完整的package.json如下:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "core-js": "^3.6.5",
    "element-ui": "^2.15.2",
    "normalize.css": "^8.0.1",
    "vue": "^2.6.12"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-standard": "^6.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^7.29.0",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^5.1.0",
    "eslint-plugin-standard": "^5.0.0",
    "eslint-plugin-vue": "^7.11.1",
    "node-sass": "^4.14.1",
    "sass-loader": "^8.0.2",
    "script-ext-html-webpack-plugin": "^2.1.5",
    "svg-sprite-loader": "^5.0.0",
    "vue-loader": "^15.9.2",
    "vue-template-compiler": "^2.6.12"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

目录结构:
前端目录结构
前端template:

<template>
  <div class="container">
    <template v-for="(section, index) in Object.keys(model)">
      <div class="title" :key="section">{{ section }}</div>
      <el-form :key="index" :model="model[section]">
        <el-form-item
          v-for="label in Object.keys(model[section])"
          :key="label"
          :label="label"
          :rules="[{ required: true, message: '请输入内容' }]"
        >
          <el-input
            :disabled="
              label === 'make_label_json' || label === 'draw_wave_sepc'
            "
            v-model="model[section][label]"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <el-button type="primary" @click="handleGet">获取数据</el-button>
    <el-button @click="handleSend">发送数据</el-button>
  </div>
</template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

前端脚本:

<script>
import request from '@/utils/request'

export default {
  name: 'MyForm',
  data () {
    return {
      model: {}
    }
  },
  methods: {
    async getConfigInfo () {
      const res = await request({
        url: '/open',
        method: 'get'
      })
      const { data } = res
      for (const key of Object.keys(data)) {
        this.$set(this.model, key, {})
        for (const attribute of Object.keys(data[key])) {
          this.$set(this.model[key], attribute, data[key][attribute])
        }
      }
    },
    handleGet () {
      this.getConfigInfo()
    },
    async setConfigInfo (config) {
      try {
        const res = await request({
          url: '/open',
          method: 'post',
          data: config
        })
        console.log(res)
        this.$message({
          type: 'success',
          message: '数据发送成功'
        })
      } catch (e) {
        console.log(e)
      }
    },
    handleSend () {
      this.setConfigInfo(this.model)
    }
  },
  created () {
    this.getConfigInfo()
  }
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

启动前端nodejs:

npm run dev
  • 1

最终效果:
附图效果1附图效果2
通过“获取数据”按钮,可以读取配置文件cc.cfg,通过“发送数据”按钮,可以提交信息,修改配置文件cc.cfg

项目完整代码,可以见这里,欢迎star ^_^

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/195228
推荐阅读
相关标签
  

闽ICP备14008679号