百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

Explain how to use Flask-SQLAlchemy with Flask

wptr33 2025-04-24 09:19 6 浏览

Flask-SQLAlchemy is an extension for Flask that simplifies working with SQLAlchemy, a powerful ORM (Object-Relational Mapping) tool for Python. Here’s how to use Flask-SQLAlchemy with Flask:


### Step 1: Install Flask-SQLAlchemy


First, you need to install Flask and Flask-SQLAlchemy. You can do this using pip:


```bash

pip install Flask Flask-SQLAlchemy

```


### Step 2: Set Up Your Flask Application


Create a new Python file (e.g., `app.py`) and set up a basic Flask application with SQLAlchemy.


```python

from flask import Flask

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)


# Configure the database URI

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Example with SQLite

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Disable track modifications


# Initialize the SQLAlchemy object

db = SQLAlchemy(app)

```


### Step 3: Define Your Models


Create models by defining classes that inherit from `db.Model`. Each class represents a table in your database.


```python

class User(db.Model):

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(150), unique=True, nullable=False)

email = db.Column(db.String(150), unique=True, nullable=False)


def __repr__(self):

return f"User('{self.username}', '{self.email}')"

```


### Step 4: Create the Database


You can create the database and tables by running the following commands in a Python shell or adding them to your script.


```python

with app.app_context():

db.create_all() # This creates the database tables

```


### Step 5: Interact with the Database


You can now create, read, update, and delete records using the models defined.


#### Adding a User


```python

@app.route('/add_user/<username>/<email>')

def add_user(username, email):

new_user = User(username=username, email=email)

db.session.add(new_user)

db.session.commit()

return f"Added user {username}!"

```


#### Querying Users


```python

@app.route('/users')

def users():

all_users = User.query.all()

return '<br>'.join([f"{user.username} - {user.email}" for user in all_users])

```


### Step 6: Run the Application


Add the following code to run the application:


```python

if __name__ == '__main__':

app.run(debug=True)

```


### Complete Example


Here’s how the complete `app.py` might look:


```python

from flask import Flask

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.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(150), unique=True, nullable=False)

email = db.Column(db.String(150), unique=True, nullable=False)


def __repr__(self):

return f"User('{self.username}', '{self.email}')"


@app.route('/add_user/<username>/<email>')

def add_user(username, email):

new_user = User(username=username, email=email)

db.session.add(new_user)

db.session.commit()

return f"Added user {username}!"


@app.route('/users')

def users():

all_users = User.query.all()

return '<br>'.join([f"{user.username} - {user.email}" for user in all_users])


if __name__ == '__main__':

with app.app_context():

db.create_all() # Create database tables

app.run(debug=True)

```


### Conclusion


By following these steps, you can easily integrate Flask-SQLAlchemy into your Flask application, allowing you to manage your database with ease. You can expand this basic setup with more complex queries, relationships, and additional features as needed.

相关推荐

Linux高性能服务器设计

C10K和C10M计算机领域的很多技术都是需求推动的,上世纪90年代,由于互联网的飞速发展,网络服务器无法支撑快速增长的用户规模。1999年,DanKegel提出了著名的C10问题:一台服务器上同时...

独立游戏开发者常犯的十大错误

...

学C了一头雾水该咋办?

学C了一头雾水该怎么办?最简单的方法就是你再学一遍呗。俗话说熟能生巧,铁杵也能磨成针。但是一味的为学而学,这个好像没什么卵用。为什么学了还是一头雾水,重点就在这,找出为什么会这个样子?1、概念理解不深...

C++基础语法梳理:inline 内联函数!虚函数可以是内联函数吗?

上节我们分析了C++基础语法的const,static以及this指针,那么这节内容我们来看一下inline内联函数吧!inline内联函数...

C语言实战小游戏:井字棋(三子棋)大战!文内含有源码

井字棋是黑白棋的一种。井字棋是一种民间传统游戏,又叫九宫棋、圈圈叉叉、一条龙、三子旗等。将正方形对角线连起来,相对两边依次摆上三个双方棋子,只要将自己的三个棋子走成一条线,对方就算输了。但是,有很多时...

C++语言到底是不是C语言的超集之一

C与C++两个关系亲密的编程语言,它们本质上是两中语言,只是C++语言设计时要求尽可能的兼容C语言特性,因此C语言中99%以上的功能都可以使用C++完成。本文探讨那些存在于C语言中的特性,但是在C++...

在C++中,如何避免出现Bug?

C++中的主要问题之一是存在大量行为未定义或对程序员来说意外的构造。我们在使用静态分析器检查各种项目时经常会遇到这些问题。但正如我们所知,最佳做法是在编译阶段尽早检测错误。让我们来看看现代C++中的一...

ESL-通过事件控制FreeSWITCH

通过事件提供的最底层控制机制,允许我们有效地利用工具箱,适时选择使用其中的单个工具。FreeSWITCH是一个核心交换与混合矩阵,它周围有几十个模块提供各种功能特性。我们完全控制了所有的即时信息,这些...

物理老师教你学C++语言(中篇)

一、条件语句与实验判断...

C语言入门指南

当然!以下是关于C语言入门编程的基础介绍和入门建议,希望能帮你顺利起步:C语言入门指南...

C++选择结构,让程序自动进行决策

什么是选择结构?正常的程序都是从上至下顺序执行,这就是顺序结构...

C++特性使用建议

1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...

C++程序员学习Zig指南(中篇)

1.复合数据类型结构体与方法的对比C++类:...

研一自学C++啃得动吗?

研一自学C++啃得动吗?在开始前我有一些资料,是我根据网友给的问题精心整理了一份「C++的资料从专业入门到高级教程」,点个关注在评论区回复“888”之后私信回复“888”,全部无偿共享给大家!!!个人...

C++关键字介绍

下表列出了C++中的常用关键字,这些关键字不能作为变量名或其他标识符名称。1、autoC++11的auto用于表示变量的自动类型推断。即在声明变量的时候,根据变量初始值的类型自动为此变量选择匹配的...