redis-om
是一个用于在 Redis 中存储和查询对象的高级库。它提供了一种简单的方式来将 Python 对象映射到 Redis 数据结构上。结合 FastAPI,你可以快速构建高性能的 API 服务。以下是使用 FastAPI 和 redis-om
的一些基本步骤。
安装依赖 首先,你需要安装 FastAPI 和 redis-om 库。
1 2 pip install fastapi[all] pip install redis-om
定义模型 使用 redis-om
定义一个模型,该模型将映射到 Redis 数据库中的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from redis_om import HashModel class Book(HashModel): title: str author: str page_count: int genre: str class Meta: global_key_prefix = "test" database = get_redis_connection( url=settings.REDIS_DSN.unicode_string(), decode_responses=True, )
在 Meta
类中,你可以指定使用的 Redis 数据库名称。
创建 CRUD 接口 接下来,你可以为你的模型创建 CRUD 接口。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 from fastapi import FastAPI, HTTPExceptionapp = FastAPI() @app.post("/books/" ) async def create_book (book: Book ): return book.save() @app.get("/books/{book_id}" ) async def read_book (book_id: str ): book = Book.get(book_id) if book is None : raise HTTPException(status_code=404 , detail="Book not found" ) return book @app.put("/books/{book_id}" ) async def update_book (book_id: str , book: Book ): book_to_update = Book.get(book_id) if book_to_update is None : raise HTTPException(status_code=404 , detail="Book not found" ) book_to_update.title = book.title book_to_update.author = book.author book_to_update.page_count = book.page_count book_to_update.genre = book.genre return book_to_update.save() @app.delete("/books/{book_id}" ) async def delete_book (book_id: str ): book = Book.get(book_id) if book is None : raise HTTPException(status_code=404 , detail="Book not found" ) book.delete() return {"detail" : "Book deleted" }
查询数据 redis-om
支持简单的查询语法,可以用来检索数据。
1 2 3 4 5 @app.get("/books/" ) async def read_books (genre: str = None ): if genre: return Book.find(Book.genre == genre) return Book.all ()
redis-om
目前处于早期阶段,变化较频繁。
redis-om
代码中很多地方还是采用的Pydantic1,如果用在Pydantic2项目中,会有大量过期告警。