search
HomeBackend DevelopmentPython TutorialHow to use ORM library for data manipulation in FastAPI

How to use ORM library for data manipulation in FastAPI

Jul 30, 2023 pm 05:00 PM
fastapiormData operations

How to use the ORM library for data operations in FastAPI

Introduction:
FastAPI is a modern Web framework based on Python. Its design is inspired by Starlette and Pydantic and is a high-performance framework. , especially suitable for building fast, scalable and high-performance RESTful API services. In FastAPI, with the help of the ORM (Object Relational Mapping) library, we can perform database operations more conveniently. This article will guide you how to use the ORM library for data manipulation in FastAPI and provide some code examples.

1. Introduction to ORM library
ORM (Object Relational Mapping) is a technology that maps data in a database into objects. The ORM library allows developers to operate the database by defining an object model without directly writing SQL statements. In FastAPI, commonly used ORM libraries include SQLAlchemy, Peewee, etc. This article uses SQLAlchemy as an example to illustrate.

2. Install and configure SQLAlchemy
Before using SQLAlchemy, we first need to install the SQLAlchemy library. You can install it through the following command:

pip install sqlalchemy

After the installation is completed, we need to set the connection configuration of the database. In FastAPI, you can add the following code to the main.py file:

from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

In the above code, we created a SQLite database and defined SessionLocal for creating a database session. SQLALCHEMY_DATABASE_URL is the URL of the database connection.

3. Define the data model
Before using ORM for data operations, we need to define the data model. Data models can be defined in the models.py file. Take a sample user model as an example. The example is as follows:

from sqlalchemy import Column, Integer, String
from database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, index=True)
    email = Column(String(50), unique=True, index=True)
    password = Column(String(100))

In the above code, we define a data model named User and specify the data table name "users". In the data model, we can define the types of each field, etc.

4. Create data tables
Before using ORM for data operations, we need to create the corresponding database table. You can add the following code to the main.py file:

Base.metadata.create_all(bind=engine)

The above code will create tables corresponding to all defined data models in the database.

5. Data operation examples
Taking the user model as an example, we will give some common data operation examples.

  1. Query all users

    from sqlalchemy.orm import Session
    from . import models
    
    def get_users(db: Session):
     return db.query(models.User).all()

    In the above code, we query all user data and return it.

  2. Querying a single user

    from sqlalchemy.orm import Session
    from . import models
    
    def get_user_by_id(db: Session, user_id: int):
     return db.query(models.User).filter(models.User.id == user_id).first()

    In the above code, we query the data of a single user by user id and return it.

  3. Create User

    from sqlalchemy.orm import Session
    from . import models, schemas
    
    def create_user(db: Session, user: schemas.UserCreate):
     hashed_password = hashlib.sha256(user.password.encode()).hexdigest()
     db_user = models.User(name=user.name, email=user.email, password=hashed_password)
     db.add(db_user)
     db.commit()
     db.refresh(db_user)
     return db_user

    In the above code, we save the incoming user data to the database and return it.

  4. Update user

    from sqlalchemy.orm import Session
    from . import models, schemas
    
    def update_user(db: Session, user_id: int, user: schemas.UserUpdate):
     db_user = db.query(models.User).filter(models.User.id == user_id).first()
     if user.name:
         db_user.name = user.name
     if user.email:
         db_user.email = user.email
     if user.password:
         db_user.password = hashlib.sha256(user.password.encode()).hexdigest()
     db.commit()
     db.refresh(db_user)
     return db_user

    In the above code, we save the incoming update data to the database through the user id.

  5. Delete User

    from sqlalchemy.orm import Session
    from . import models
    
    def delete_user(db: Session, user_id: int):
     db_user = db.query(models.User).filter(models.User.id == user_id).first()
     db.delete(db_user)
     db.commit()
     return {'message': f"User {user_id} deleted successfully"}

    In the above code, we delete user data from the database by user id.

Conclusion:
Through the above code examples, we can see that it is relatively simple to use the ORM library for data operations in FastAPI. With the help of the ORM library, we do not need to write SQL statements directly, but can perform database operations through the object model, making the code more concise and readable. I hope this article will help you use the ORM library for data operations in your FastAPI project.

The above is the detailed content of How to use ORM library for data manipulation in FastAPI. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment