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

Explain how to use Flask-SQLAlchemy with Flask

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

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.

相关推荐

台积电提出SRAM存内计算新方法,能效比可达89TOPS/W

芯东西(公众号:aichip001)编译|高歌编辑|云鹏芯东西3月16日消息,近期,台积电的研究人员在ISSCC2021会议上公布了一种改良的SRAM存储器阵列,该SRAM阵列采用22nm工...

Golang中如何判断两个slice是否相等?

在Golang中,要判断两个slice是否相等是不能直接使用==运算符的(==只能说明两个slice是否指向同一个底层数组)。如果两个slice的底层数组相同,但长度或容量不同...

JS入门基础知识(js基础知识总结笔记)

JS对象操作对象增删改查创建对象letobj={}新增属性obj.a=1修改属性obj.a='a'...

趣谈JS二进制:File、Blob、FileReader、ArrayBuffer、Base64

大家好,我是Echa。好久没跟粉丝们细聊JavaScript那点事了。做一名全栈工程师,JS基础还是要打牢,这样的话不管底层业务逻辑以及第三方框架怎么变化,都离不开基础。本文文章属于基础篇,阅读有点...

告别 substr() 和 substring()?更可靠的 JavaScript 字符串截取方法

JavaScript提供了三个主要的字符串截取方法:...

golang第九天,切片(slice)介绍(golang 切片作为参数)

什么是切片golang切片是对数组的抽象。go的数组长度不可改变,在特定场景中这样的集合就不太适用,go中提供了一种灵活,功能强悍的内置类型切片(“动态数组”),与数组相比切片的长度是不固定的,可以追...

Go语言零到一:数组(go struct数组)

引言...

你说你熟悉Slice,这道slice题你能答对吗?

每当你花费大量时间使用某种特定工具时,深入了解它并了解如何高效地使用它是很值得的。...

Python 3.14七大新特性总结:从t-string模板到GIL并发优化

Python3.14已进入测试阶段,根据PEP745发布计划,该版本已停止引入新功能,也就是说新特征就应该已经固定下来了。所以本文基于当前最新的beta2版本,深入分析了Python3.14中...

Python 幕后:Python导入import的工作原理

更多互联网精彩资讯、工作效率提升关注【飞鱼在浪屿】(日更新)Python最容易被误解的方面其中之一是import。...

Python元类实现自动化编程的正确姿势

元类是Python中用于创建类的类。通过元类机制,开发者可在运行时动态创建和修改类,为框架开发、设计模式实现和高级架构设计提供核心支持。在Python语言的高级特性中,元类占据着独特而重要的地位。作...

Python字符串详解与示例(python字符串类型及操作)

艾瑞巴蒂字符串的干货来了,字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍下字符串的特性,操作和方法,和一些示例来吧道友:1.字符串的创建在python中字符串可以永单引号(...

恕我直言!你对Python里的import一无所知

文章来源:https://mp.weixin.qq.com/s/4WAOU_Lzy651IE-2zZSFfQ原文作者:写代码的明哥...

Python基础:字符串操作(python字符串的用法)

字符串是Python中最常用的数据类型之一,用于表示文本数据。我们将学习如何对字符串进行常见的操作,包括创建、访问、修改和处理字符串。通过掌握这些技巧,您将能够更好地处理和操作文本数据。让我们开始吧!...

Python 中 字符串处理的高效方法,不允许你还不知道

以下是Python中字符串处理的高效方法...