Home  >  Article  >  Backend Development  >  How to use ORM library for data manipulation in FastAPI

How to use ORM library for data manipulation in FastAPI

王林
王林Original
2023-07-30 17:00:412708browse

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