Uniapp+python快速构建跨平台应用

以下是基于 UniApp (前端)和 Python(后端)的交互功能实现方案,包含完整的代码示例和步骤说明。我们将实现一个简单的用
户信息提交与查询系统,前端通过 UniApp 收集用户输入并发送到 Python 后端,后端处理后返回结果。

1. 技术栈选择

  • 前端:UniApp(Vue语法,跨平台支持 H5/小程序/App)
  • 后端:Python + Flask(轻量级Web框架)
  • 通信协议:HTTP(RESTful API)
  • 数据存储:SQLite(轻量级数据库,适合本地测试)

2. 后端实现(Python + Flask)

步骤1:创建Flask项目

1
2
3
4
5
mkdir uniapp_python_backend
cd uniapp_python_backend
python3 -m venv venv # 创建虚拟环境
source venv/bin/activate # 激活虚拟环境(Linux/macOS)
pip install flask flask-cors sqlite3 # 安装依赖

步骤2:编写Flask后端代码

创建app.py:

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
from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3

app = Flask(__name__)
CORS(app) # 允许跨域请求(UniApp开发环境需要)

# 初始化 SQLite 数据库
def init_db():
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
)
''')
conn.commit()
conn.close()

# 添加用户接口
@app.route('/api/add_user', methods=['POST'])
def add_user():
data = request.json
name = data.get('name')
email = data.get('email')

if not name or not email:
return jsonify({'error': 'Name and email are required!'}), 400

try:
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)', (name, email))
conn.commit()
conn.close()
return jsonify({'message': 'User added successfully!'}), 201
except sqlite3.IntegrityError:
return jsonify({'error': 'Email already exists!'}), 400

# 查询所有用户接口
@app.route('/api/get_users', methods=['GET'])
def get_users():
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
conn.close()
return jsonify([{'id': user[0], 'name': user[1], 'email': user[2]} for user in users])

if __name__ == '__main__':
init_db()
app.run(debug=True, port=5000)

步骤3:启动后端服务

1
python app.py

后端服务默认运行在http://localhost:5000。

3. 前端实现(UniApp)

步骤1:创建 UniApp 项目

使用 HBuilderX 创建一个默认的 UniApp 项目。

步骤2:编写页面逻辑

在pages/index/index.vue中实现用户提交和查询功能:

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<template>
<view class="container">
<view class="form">
<input v-model="name" placeholder="请输入姓名" class="input" />
<input v-model="email" placeholder="请输入邮箱" class="input" />
<button @click="submitUser" class="button">提交</button>
</view>

<view class="user-list">
<text class="title">用户列表</text>
<view v-for="user in users" :key="user.id" class="user-item">
<text>{{ user.name }} ({{ user.email }})</text>
</view>
<button @click="fetchUsers" class="button">刷新列表</button>
</view>
</view>
</template>

<script>
export default {
data() {
return {
name: '',
email: '',
users: []
}
},
methods: {
async submitUser() {
if (!this.name || !this.email) {
uni.showToast({ title: '请填写完整信息', icon: 'none' });
return;
}

try {
const res = await uni.request({
url: 'http://localhost:5000/api/add_user',
method: 'POST',
data: { name: this.name, email: this.email },
header: { 'Content-Type': 'application/json' }
});

if (res[1].statusCode === 201) {
uni.showToast({ title: '提交成功' });
this.name = '';
this.email = '';
this.fetchUsers(); // 刷新列表
} else {
uni.showToast({ title: res[1].data.error, icon: 'none' });
}
} catch (err) {
uni.showToast({ title: '请求失败', icon: 'none' });
}
},

async fetchUsers() {
try {
const res = await uni.request({
url: 'http://localhost:5000/api/get_users',
method: 'GET'
});
this.users = res[1].data;
} catch (err) {
uni.showToast({ title: '获取用户列表失败', icon: 'none' });
}
}
},
onLoad() {
this.fetchUsers(); // 页面加载时获取用户列表
}
}
</script>

<style>
.container {
padding: 20px;
}
.input {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
width: 100%;
}
.button {
background-color: #007AFF;
color: white;
padding: 10px;
border-radius: 5px;
text-align: center;
margin-bottom: 20px;
}
.user-list {
margin-top: 20px;
}
.user-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
.title {
font-size: 18px;
font-weight: bold;
display: block;
margin-bottom: 10px;
}
</style>

4. 运行与测试

  1. 启动后端:
1
python app.py
  1. 运行 UniApp:

    • 在 HBuilderX 中选择运行到浏览器(H5)或微信小程序模拟器。
  2. 测试功能:

    • 提交用户信息(姓名 + 邮箱)。
    • 点击“刷新列表”查看所有用户。

5. 关键点说明

  1. 跨域问题:Flask需使用flask-cors允许 UniApp的跨域请求。
  2. 数据持久化:SQLite适合本地测试,生产环境可替换为MySQL/PostgreSQL。
  3. UniApp 请求:使用uni.request发送 HTTP 请求,注意Content-Type: application/json。
  4. 调试技巧:
    • 后端日志:查看 Flask 控制台输出。
    • 前端调试:使用console.log或uni.showToast提示错误。

6. 扩展功能

  • 用户登录:增加 JWT 认证。
  • 图片上传:使用uni.uploadFile接口。
  • WebSocket 实时通信:适用于聊天室等场景。

最终效果

  • 前端(UniApp)提交数据 → 后端(Python Flask)处理并存储 → 前端展示结果。
  • 适用于问卷调查、数据收集等场景。
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2023-2025 John Doe
  • Visitors: | Views:

请我喝杯茶吧~

支付宝
微信