flask前后端分离实现增删改查
时间: 2023-06-16 20:02:32 浏览: 139
前后端分离的实现方式有很多种,以下是一种基于 Flask 和 Vue.js 的实现方式:
1. 后端使用 Flask 框架搭建 API,可以使用 Flask-RESTful 库来方便地实现 RESTful API。例如:
```python
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
tasks = [
{
'id': 1,
'title': 'Task 1',
'description': 'This is task 1',
'done': False
},
{
'id': 2,
'title': 'Task 2',
'description': 'This is task 2',
'done': False
}
]
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
return jsonify({'task': task[0]})
@app.route('/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ''),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
if not request.json:
abort(400)
task[0]['title'] = request.json.get('title', task[0]['title'])
task[0]['description'] = request.json.get('description', task[0]['description'])
task[0]['done'] = request.json.get('done', task[0]['done'])
return jsonify({'task': task[0]})
@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
abort(404)
tasks.remove(task[0])
return jsonify({'result': True})
if __name__ == '__main__':
app.run(debug=True)
```
2. 前端使用 Vue.js 框架搭建页面,通过 AJAX 调用后端提供的 API 来实现增删改查功能。例如:
```html
<!DOCTYPE html>
<html>
<head>
<title>Tasks</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<v-app>
<v-container>
<v-text-field label="Title" v-model="title"></v-text-field>
<v-text-field label="Description" v-model="description"></v-text-field>
<v-btn color="primary" @click="createTask">Create</v-btn>
<v-data-table :headers="headers" :items="tasks" :search="search" item-key="id">
<template v-slot:top>
<v-toolbar flat>
<v-toolbar-title>Tasks</v-toolbar-title>
<v-spacer></v-spacer>
<v-text-field v-model="search" append-icon="search" label="Search"></v-text-field>
</v-toolbar>
</template>
<template v-slot:item.actions="{ item }">
<v-icon small class="mr-2" @click="editTask(item)">edit</v-icon>
<v-icon small @click="deleteTask(item)">delete</v-icon>
</template>
</v-data-table>
<v-dialog v-model="dialog" persistent max-width="600px">
<v-card>
<v-card-title>
<span class="headline">{{ formTitle }}</span>
</v-card-title>
<v-card-text>
<v-text-field label="Title" v-model="editedTask.title"></v-text-field>
<v-text-field label="Description" v-model="editedTask.description"></v-text-field>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="blue darken-1" text @click="closeDialog">Cancel</v-btn>
<v-btn color="blue darken-1" text @click="saveTask">Save</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>
</v-app>
</div>
<script>
new Vue({
el: '#app',
data: {
title: '',
description: '',
headers: [
{ text: 'ID', value: 'id' },
{ text: 'Title', value: 'title' },
{ text: 'Description', value: 'description' },
{ text: 'Done', value: 'done' },
{ text: 'Actions', value: 'actions' }
],
tasks: [],
search: '',
dialog: false,
formTitle: '',
editedTask: {
id: 0,
title: '',
description: '',
done: false
}
},
created: function () {
this.fetchTasks();
},
methods: {
fetchTasks: function () {
axios.get('/tasks')
.then(response => {
this.tasks = response.data.tasks;
})
.catch(error => {
console.log(error);
});
},
createTask: function () {
axios.post('/tasks', {
title: this.title,
description: this.description
})
.then(response => {
this.tasks.push(response.data.task);
this.title = '';
this.description = '';
})
.catch(error => {
console.log(error);
});
},
editTask: function (task) {
this.formTitle = 'Edit Task';
this.editedTask = Object.assign({}, task);
this.dialog = true;
},
saveTask: function () {
axios.put('/tasks/' + this.editedTask.id, {
title: this.editedTask.title,
description: this.editedTask.description,
done: this.editedTask.done
})
.then(response => {
var index = this.tasks.findIndex(task => task.id == response.data.task.id);
Vue.set(this.tasks, index, response.data.task);
this.dialog = false;
})
.catch(error => {
console.log(error);
});
},
deleteTask: function (task) {
axios.delete('/tasks/' + task.id)
.then(response => {
var index = this.tasks.findIndex(t => t.id == task.id);
this.tasks.splice(index, 1);
})
.catch(error => {
console.log(error);
});
},
closeDialog: function () {
this.dialog = false;
setTimeout(() => {
this.editedTask = {
id: 0,
title: '',
description: '',
done: false
};
}, 300);
}
}
});
</script>
</body>
</html>
```
以上代码仅供参考,具体实现方式可以根据实际需求进行调整。
阅读全文