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.
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.
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.
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.
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.
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!