miniProgram/vue.js + flask全栈小案例

项目结构

由于该项目简单,主要有app.py, logic.py,index.html,books.db构成
项目结构



建立数据库

新建数据库连接

新建一个数据库连接

点击test connection按钮
连接成功

点击ok,然后新建一个表,关于pycharm如何新建一个sqlite数据表和添加数据,这里就不说了,网上搜一下就好了。
表中的数据

好了,到了这一步数据库的准备工作就完成了。





Vue.js与flask结合

前端的模板:
delimiters: ["[[", “]]”]这里是因为JinJia2双括号语法和vue.js冲突了,所以把vue.js的双括号限定改为双中括号限定

 this.$http.get('/api/books').then(rsp => {
                    this.books = rsp.body
                }, err => {
                    console.log("Error")
                })

这一小段代码是用到了vue-resource,利用它的http模块进行请求,如果成功则把返回的数据复制给this(vue对象)的books属性,失败则在命令行中输出 "Error"的字符创。


index.html

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask & Vue.js 全栈小案例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
<div id="app">
    <h1>Flask & Vue.js {{ title }}</h1>
    <table border="1" cellpadding="10" cellspacing="5">
        <tr>
            <th>#</th>
            <th>标题</th>
            <th>作者</th>
            <th>定价</th>
        </tr>
        <tr v-for="book in books">
            <td>[[ book.id ]]</td>
            <td>[[ book.title ]]</td>
            <td>[[ book.author ]]</td>
            <td>[[ book.price ]]</td>
        </tr>
    </table>
</div>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            books: []
        },
        delimiters: ["[[", "]]"],
        mounted: function () {
            this.fetchData();
        },
        methods: {
            fetchData() {
                this.$http.get('/api/books').then(rsp => {
                    this.books = rsp.body
                }, err => {
                    console.log("Error")
                })
            }
        }
    })

</script>
</body>
</html>



后端app.py的代码

from flask import Flask
from flask import jsonify, render_template

import logic

app = Flask(__name__)


@app.route('/')
def home():
    return render_template("index.html", title="andy dennis")


@app.route("/api/books")
def books():
    rows = logic.get_books()
    return jsonify(rows)


@app.route('/wei_xin', methods=['get', 'post'])
def wei_xin():
    return "Hello! I'm from Flask."

逻辑部分由logic.py处理

import sqlite3


def get_books():
    conn = sqlite3.connect("books.db")
    # 为了待会儿cur.execute(sql).fetchall()返回(表头,数据)的元组
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    sql = "select * from book"
    # 返回的是元素是元组的列表
    rows = cur.execute(sql).fetchall()
    # 将其转化为元素为字典的列表
    rows = [dict(row) for row in rows]
    print(rows)
    return rows




微信小程序

我试验过,选择云开发和不选择云开发都可以
项目结构

这里我改了一下这个app.json。不过不是主要的部分。只是想改变上面导航栏的背景颜色。
app.json

{
  "pages": [
    "pages/index/index"
  ],
  "window": {
    "backgroundColor": "#F6F6F6",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#45b97c",
    "navigationBarTitleText": "localhost",
    "navigationBarTextStyle": "black"
  },
  "sitemapLocation": "sitemap.json",
  "style": "v2"
}

小程序样子

pages/index/index.wxml
注意一下这里的wx:for语法。

<!--index.wxml-->
<view class="myview">
  <text class="content">{{message}}</text>
</view>
<view class="head">
  <text class="title">id</text> 
  <text class="title">title</text> 
  <text class="title">author</text> 
  <text class="title">price</text>
</view>
<view wx:for="{{data}}">
  <text class="title">{{item.id}}</text> 
  <text class="title">{{item.title}}</text> 
  <text class="title">{{item.author}}</text> 
  <text class="title">{{item.price}}</text>
</view>
<button bindtap="reqBack">获取服务器数据</button>

pages/index/index.wxss
/**index.wxss**/
.myview{
  font-size: 50rpx;
  color: #ea66a6;
  margin-top: 120rpx;
  text-align: center;
}

.head{
  margin-top: 60rpx; 
  color: #f47920;
}

.title{
  display: inline-block;
  width: 180rpx;
  text-align: center;
}

button{
  color: #fffffb;
  margin-top: 60rpx; 
  background-color: #84bf96;
}

pages/index/index.js

//index.js
const app = getApp()

Page({
  data: {
    message: 'Hello',
    data: []
  },
  reqBack: function(){
    wx.request({
      url: 'http://127.0.0.1:5000/wei_xin',
      method: 'get',
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success: res => {
        console.log(res.data)
        this.setData({
          message: res.data
        })
      },
      fail: err => {
        console.log(err)
      }
    })

    wx.request({
      url: 'http://127.0.0.1:5000/api/books',
      method: 'get',
      header:{
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        console.log(res.data)
        this.setData({
          data: res.data
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  }
})

值得注意一下这里的wx.request函数。




运行效果

页面数据

print(row)

小程序页面

其实运行过程中数据库增加新的书籍,只要页面一刷新,就会看到添加的数据啦。

猜你喜欢

转载自blog.csdn.net/weixin_43850253/article/details/107642070