如何在flask网站中使用thonny通过get指令将数据写入数据库中,给出详细代码
时间: 2024-04-30 08:20:40 浏览: 17
在Flask网站中使用Thonny通过GET请求将数据写入数据库需要进行以下步骤:
1. 确保已经安装了需要的Python模块,如Flask、SQLAlchemy等。
2. 创建一个Flask应用程序,并在其中导入所需的模块:
```python
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
```
3. 配置数据库连接和模型:
```python
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
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)
```
4. 创建一个路由,该路由将接收GET请求并将数据写入数据库:
```python
@app.route('/add_user', methods=['GET'])
def add_user():
name = request.args.get('name')
email = request.args.get('email')
user = User(name=name, email=email)
db.session.add(user)
db.session.commit()
return 'User added successfully'
```
5. 启动应用程序:
```python
if __name__ == '__main__':
app.run(debug=True)
```
完整代码如下:
```python
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
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)
@app.route('/add_user', methods=['GET'])
def add_user():
name = request.args.get('name')
email = request.args.get('email')
user = User(name=name, email=email)
db.session.add(user)
db.session.commit()
return 'User added successfully'
if __name__ == '__main__':
app.run(debug=True)
```
可以通过访问http://localhost:5000/add_user?name=xxx&email=xxx 来向数据库中添加数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)