flask如何更新数据表
时间: 2023-11-02 13:03:20 浏览: 42
Flask 本身并不提供更新数据表的功能,但是可以通过调用数据库管理系统提供的 API 来实现。常见的数据库管理系统包括 MySQL、PostgreSQL、SQLite 等。以下是一个示例代码,以使用 SQLAlchemy 操作 MySQL 数据库为例:
```python
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/db_name'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.name}>'
@app.route('/update_user/<int:user_id>', methods=['POST'])
def update_user(user_id):
user = User.query.get(user_id)
if not user:
return 'User not found', 404
user.name = request.form['name']
user.email = request.form['email']
db.session.commit()
return 'User updated successfully', 200
```
以上代码定义了一个 `User` 模型,包含了 `id`、`name`、`email` 三个属性。在路由 `/update_user/<int:user_id>` 上响应 `POST` 请求,接受传入的 `name` 和 `email`,将其更新到指定的用户记录中,并提交到 MySQL 数据库中。通过使用 Flask-RESTful,可以更方便的实现 RESTful 风格的 API。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)