用python和vue生成一个用户管理系统
时间: 2024-06-08 10:06:00 浏览: 140
用户管理系统包含用户注册、登录、修改密码、查看个人信息等功能,可以使用Python编写后端API接口,Vue.js编写前端页面。
首先,使用Python的Flask框架搭建后端API接口,可以使用SQLAlchemy来操作数据库。具体步骤如下:
1. 安装Flask和SQLAlchemy
```
pip install flask
pip install sqlalchemy
```
2. 创建Flask应用程序
```python
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
```
3. 创建数据库模型
```python
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(50), unique=True, nullable=False)
phone = db.Column(db.String(20), unique=True, nullable=False)
```
4. 创建API接口
```python
from flask import request, jsonify
@app.route('/api/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get('username')
password = data.get('password')
email = data.get('email')
phone = data.get('phone')
user = User.query.filter_by(username=username).first()
if user:
return jsonify({'status': 'error', 'message': 'Username already exists.'})
user = User(username=username, password=password, email=email, phone=phone)
db.session.add(user)
db.session.commit()
return jsonify({'status': 'success', 'message': 'User registered successfully.'})
@app.route('/api/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
user = User.query.filter_by(username=username, password=password).first()
if not user:
return jsonify({'status': 'error', 'message': 'Invalid username or password.'})
return jsonify({'status': 'success', 'message': 'User logged in successfully.'})
@app.route('/api/user', methods=['GET'])
def get_user():
username = request.args.get('username')
user = User.query.filter_by(username=username).first()
if not user:
return jsonify({'status': 'error', 'message': 'User not found.'})
return jsonify({'status': 'success', 'data': {'username': user.username, 'email': user.email, 'phone': user.phone}})
@app.route('/api/user', methods=['PUT'])
def update_user():
data = request.get_json()
username = data.get('username')
email = data.get('email')
phone = data.get('phone')
user = User.query.filter_by(username=username).first()
if not user:
return jsonify({'status': 'error', 'message': 'User not found.'})
user.email = email
user.phone = phone
db.session.commit()
return jsonify({'status': 'success', 'message': 'User updated successfully.'})
```
现在,我们已经完成了后端API接口的编写。接下来,使用Vue.js编写前端页面。具体步骤如下:
1. 安装Vue.js和Vue Router
```
npm install vue
npm install vue-router
```
2. 创建Vue组件
```javascript
// 登录组件
const LoginComponent = {
template: `
<div>
<h2>Login</h2>
<form @submit.prevent="login">
<div>
<label>Username:</label>
<input type="text" v-model="username">
</div>
<div>
<label>Password:</label>
<input type="password" v-model="password">
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
<div v-if="message">{{ message }}</div>
</div>
`,
data() {
return {
username: '',
password: '',
message: ''
}
},
methods: {
login() {
axios.post('/api/login', {
username: this.username,
password: this.password
}).then(response => {
if (response.data.status === 'success') {
this.message = response.data.message
this.$router.push('/dashboard')
} else {
this.message = response.data.message
}
})
}
}
}
// 注册组件
const RegisterComponent = {
template: `
<div>
<h2>Register</h2>
<form @submit.prevent="register">
<div>
<label>Username:</label>
<input type="text" v-model="username">
</div>
<div>
<label>Password:</label>
<input type="password" v-model="password">
</div>
<div>
<label>Email:</label>
<input type="email" v-model="email">
</div>
<div>
<label>Phone:</label>
<input type="text" v-model="phone">
</div>
<div>
<button type="submit">Register</button>
</div>
</form>
<div v-if="message">{{ message }}</div>
</div>
`,
data() {
return {
username: '',
password: '',
email: '',
phone: '',
message: ''
}
},
methods: {
register() {
axios.post('/api/register', {
username: this.username,
password: this.password,
email: this.email,
phone: this.phone
}).then(response => {
if (response.data.status === 'success') {
this.message = response.data.message
this.$router.push('/login')
} else {
this.message = response.data.message
}
})
}
}
}
// 个人信息组件
const ProfileComponent = {
template: `
<div>
<h2>Profile</h2>
<div>
<label>Username:</label>
<span>{{ username }}</span>
</div>
<div>
<label>Email:</label>
<input type="email" v-model="email">
</div>
<div>
<label>Phone:</label>
<input type="text" v-model="phone">
</div>
<div>
<button @click="update">Update</button>
</div>
<div v-if="message">{{ message }}</div>
</div>
`,
data() {
return {
username: '',
email: '',
phone: '',
message: ''
}
},
methods: {
getUser() {
axios.get('/api/user', {
params: {
username: localStorage.getItem('username')
}
}).then(response => {
if (response.data.status === 'success') {
this.username = response.data.data.username
this.email = response.data.data.email
this.phone = response.data.data.phone
}
})
},
update() {
axios.put('/api/user', {
username: localStorage.getItem('username'),
email: this.email,
phone: this.phone
}).then(response => {
if (response.data.status === 'success') {
this.message = response.data.message
} else {
this.message = response.data.message
}
})
}
},
mounted() {
this.getUser()
}
}
// 未授权组件
const UnauthorizedComponent = {
template: `
<div>
<h2>401 Unauthorized</h2>
</div>
`
}
// 未找到组件
const NotFoundComponent = {
template: `
<div>
<h2>404 Not Found</h2>
</div>
`
}
```
3. 创建Vue路由
```javascript
const routes = [
{ path: '/', redirect: '/login' },
{ path: '/login', component: LoginComponent },
{ path: '/register', component: RegisterComponent },
{ path: '/dashboard', component: ProfileComponent, meta: { requiresAuth: true } },
{ path: '/unauthorized', component: UnauthorizedComponent },
{ path: '*', component: NotFoundComponent }
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!localStorage.getItem('username')) {
next('/unauthorized')
} else {
next()
}
} else {
next()
}
})
```
4. 创建Vue实例
```javascript
new Vue({
el: '#app',
router
})
```
现在,我们已经完成了用户管理系统的开发。可以使用以下命令启动应用程序:
```
python app.py
```
```
npm run serve
```
访问http://localhost:8080即可开始使用用户管理系统。
阅读全文