Compare commits
14 Commits
526bcfce0a
...
main
Author | SHA1 | Date | |
---|---|---|---|
f1edcb8e54 | |||
a6aff36585 | |||
2cc8af0fef | |||
9b24962de9 | |||
92703a333b | |||
4e382fe353 | |||
8f03ab7a18 | |||
d1ff601e9b | |||
851938dd13 | |||
5b278d9491 | |||
a4bc6b1eed | |||
5d86fb7c4a | |||
de898dec6a | |||
5ef3a9eafe |
@ -64,7 +64,7 @@ author:
|
||||
- label: "sahinakkaya"
|
||||
icon: "fab fa-fw fa-github"
|
||||
url: "https://github.com/sahinakkaya"
|
||||
- label: "Asocia"
|
||||
- label: "sahinakkaya"
|
||||
icon: "fab fa-fw fa-stack-overflow"
|
||||
url: "https://stackoverflow.com/users/9608759"
|
||||
- label: "@sahinakkayadev"
|
||||
@ -75,7 +75,7 @@ author:
|
||||
url: "mailto:sahin@sahinakkaya.dev"
|
||||
- label: "Resume"
|
||||
icon: "fas fa-fw fa-id-card"
|
||||
url: "/assets/docs/resume.pdf"
|
||||
url: "https://resume.sahinakkaya.dev"
|
||||
|
||||
|
||||
masthead_title: "/home/sahin/"
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "First blog post"
|
||||
date: 2021-12-25 02:54:08 +0300
|
||||
classes: wide
|
||||
excerpt: Hello, World!* So here I am and welcome to my first blog. Having a personal space on the Internet has been a dream for me for years and I am happy that it fi...
|
||||
---
|
||||
<style>
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "Stop cat-pipe'ing, You Are Doing It Wrong!"
|
||||
date: 2022-01-01 18:00:00 +0300
|
||||
classes: wide
|
||||
tags: cat grep linux command-line
|
||||
---
|
||||
```bash
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "Automatically Build and Deploy Your Site using GitHub Actions and Webhooks"
|
||||
date: 2022-01-04 20:40:00 +0300
|
||||
classes: wide
|
||||
tags: github-actions github-webhooks ci-cd
|
||||
---
|
||||
In this post I will explain how you can use GitHub to automate the build and deployment processes that you have. I am going to automate the deployment of this site but you can do whatever you want. Just understanding the basics will be enough.
|
||||
|
@ -2,6 +2,7 @@
|
||||
title: "Using ffmpeg for Simple Video Editing"
|
||||
date: 2022-01-21 23:40:00 +0300
|
||||
tags: cli ffmpeg
|
||||
classes: wide
|
||||
excerpt:
|
||||
---
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "Creating a *Useless* User"
|
||||
date: 2022-02-27 16:40:00 +0300
|
||||
classes: wide
|
||||
tags: linux permissions privileges
|
||||
---
|
||||
## Story
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "SSH into Machine That Is Behind a Private Network"
|
||||
date: 2022-02-27 00:40:00 +0300
|
||||
classes: wide
|
||||
tags: ssh private-network remote-port-forwarding
|
||||
---
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "Never Get Trapped in Grub Rescue Again!"
|
||||
date: 2022-03-03 03:46:00 +0300
|
||||
classes: wide
|
||||
tags: linux grub partition uefi
|
||||
---
|
||||
|
||||
|
@ -2,6 +2,7 @@
|
||||
title: "Confession Time"
|
||||
date: 2022-04-08 18:46:00 +0300
|
||||
last_modified_at: 2022-04-13
|
||||
classes: wide
|
||||
tags: ssl
|
||||
---
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "Rant: Stop whatever you are doing and learn how licenses work"
|
||||
date: 2022-06-22 10:46:00 +0300
|
||||
classes: wide
|
||||
tags: copilot license github
|
||||
---
|
||||
Recently, Github [announced](https://github.blog/changelog/2022-06-21-github-copilot-is-now-available-to-individual-developers/)
|
||||
|
@ -1,5 +1,6 @@
|
||||
---
|
||||
title: "Recap of 2022"
|
||||
classes: wide
|
||||
date: 2022-12-29 23:22:08 +0300
|
||||
---
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
---
|
||||
title: "Hot-Reload Long Running Shell Scripts (feat. trap / kill)"
|
||||
date: 2023-01-16 00:48:08 +0300
|
||||
classes: wide
|
||||
tags: trap kill linux
|
||||
---
|
||||
|
||||
|
@ -0,0 +1,427 @@
|
||||
---
|
||||
title: "Conditionally load SQLAlchemy model relationships in FastAPI"
|
||||
date: 2024-08-04 12:55:01 +0300
|
||||
classes: wide
|
||||
tags: fastapi sqlalchemy pydantic
|
||||
---
|
||||
|
||||
Suppose you have a FastAPI app responsible for talking with database via sqlalchemy and retrieving data. The sqlalchemy models have some `relationship`s and the job of your app is exposing this database models with or without relationships based on the operation. You can't make use of relationship loading strategies (`'selectin'`, `'joined'` etc.) because FastAPI tries to convert the result to pydantic schemas and pydantic tries to load the relationship even though you don't need it to load for that specific operation. There are three things you can do:
|
||||
|
||||
1. *Define the loading strategy in your sqlalchemy models and create different pydantic schemas for the same entity including/excluding different fields. (i.e. if you don't need to load `Book.reviews` for specific endpoint, create a new pydantic schema for books without including `reviews`). After that, create different routes for returning correct schema. (`get_books_with_reviews`, `get_books_without_reviews` etc.)* <br/>
|
||||
This is the easiest option. Once you decided how each field should be loaded, you only need to create different pydantic schema for loading different fields. The downside is that you will have a lot of schemas and maintaining them will be hard.
|
||||
2. *Create a pydantic schema with all fields and declare some fields as nullable. Do not load anything by default in sqlalchemy models (`lazy='noload'`). Create different routes returning the same schema but inside the routes, manually edit the `query.options` to load different fields.* <br/>
|
||||
This is what we were doing in our project. Only implementing the routes that we need 90% of the time was working fine for us. If we need more data, we were doing a second request to our API and merging the results. This becomes tedious after some time which is why we decided to move away from it.
|
||||
3. *Somehow get the loading options as input from users of your API and return what is requested.* <br/>
|
||||
That's it! If such endpoint exists all our problems would be solved. In this post, we will implement that!
|
||||
|
||||

|
||||
|
||||
|
||||
I will first include code snippets which doesn't have any special logic then add the solution at the end. Here is the database schema I will use:
|
||||
|
||||

|
||||
|
||||
|
||||
Let's create our sqlalchemy models:
|
||||
|
||||
```python
|
||||
# models.py
|
||||
from sqlalchemy import ForeignKey, create_engine
|
||||
from sqlalchemy.orm import (
|
||||
Mapped,
|
||||
Session,
|
||||
mapped_column,
|
||||
relationship,
|
||||
DeclarativeBase,
|
||||
)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class Author(Base):
|
||||
__tablename__ = "authors"
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column()
|
||||
awards = relationship("Award", lazy="noload")
|
||||
|
||||
books: Mapped[list["Book"]] = relationship(lazy="noload", back_populates="author")
|
||||
|
||||
|
||||
class Award(Base):
|
||||
__tablename__ = "awards"
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
|
||||
name: Mapped[str] = mapped_column()
|
||||
year: Mapped[int] = mapped_column()
|
||||
|
||||
|
||||
class Book(Base):
|
||||
__tablename__ = "books"
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
title: Mapped[str] = mapped_column()
|
||||
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"), nullable=True)
|
||||
|
||||
reviews: Mapped[list["Review"]] = relationship(lazy="noload", back_populates="book")
|
||||
author = relationship("Author", lazy="noload", back_populates="books")
|
||||
|
||||
|
||||
class Review(Base):
|
||||
__tablename__ = "reviews"
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
text: Mapped[str] = mapped_column()
|
||||
book_id: Mapped[int] = mapped_column(ForeignKey("books.id"))
|
||||
|
||||
book: Mapped["Book"] = relationship(lazy="noload")
|
||||
|
||||
```
|
||||
|
||||
These are our database models. For the sake of our example, I will include the code to add some data to our database.
|
||||
```python
|
||||
# models.py
|
||||
|
||||
engine = create_engine("sqlite://", echo=True)
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
|
||||
session = Session(engine)
|
||||
with session.begin():
|
||||
book1 = Book(title="Book 1")
|
||||
session.add(book1)
|
||||
session.flush()
|
||||
review1 = Review(text="Review 1", book_id=book1.id)
|
||||
review2 = Review(text="Review 2", book_id=book1.id)
|
||||
session.add_all([review1, review2])
|
||||
session.flush()
|
||||
|
||||
author = Author(name="Author 1")
|
||||
session.add(author)
|
||||
session.flush()
|
||||
book2 = Book(title="Book 2", author_id=author.id)
|
||||
book1.author_id = author.id
|
||||
session.add(book2)
|
||||
session.add(book1)
|
||||
session.flush()
|
||||
|
||||
author2 = Author(
|
||||
name="Author 2",
|
||||
awards=[Award(name="Award 1", year=2021), Award(name="Award 2", year=2024)],
|
||||
)
|
||||
session.add(author2)
|
||||
session.flush()
|
||||
book3 = Book(title="Book 3", author_id=author2.id)
|
||||
session.add(book3)
|
||||
|
||||
session.flush()
|
||||
review3 = Review(text="Review 3", book_id=book3.id)
|
||||
session.add(review3)
|
||||
session.flush()
|
||||
```
|
||||
|
||||
|
||||
Now that we have our database ready, let's create pydantic schemas
|
||||
|
||||
```python
|
||||
# schemas.py
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ReviewSchema(BaseModel):
|
||||
id: int
|
||||
text: str
|
||||
book_id: int
|
||||
book: "BookSchema | None" = None
|
||||
|
||||
|
||||
class BookSchema(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
author_id: int
|
||||
author: "AuthorSchema | None" = None
|
||||
reviews: list[ReviewSchema] = []
|
||||
|
||||
|
||||
class AwardSchema(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
year: int
|
||||
|
||||
|
||||
class AuthorSchema(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
books: list[BookSchema] = []
|
||||
awards: list[AwardSchema] = []
|
||||
|
||||
```
|
||||
|
||||
And lastly, we need to initialize FastAPI app to interact with our database. Let's create a very simple app for exposing `Author`s and `Review`s outside.
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
from models import Author, engine
|
||||
from schemas import AuthorSchema, ReviewSchema
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/authors", response_model=list[AuthorSchema])
|
||||
async def get_authors():
|
||||
session = Session(engine)
|
||||
query = session.query(Author)
|
||||
return query.all()
|
||||
|
||||
|
||||
@app.get("/reviews", response_model=list[ReviewSchema])
|
||||
async def get_reviews():
|
||||
session = Session(engine)
|
||||
query = session.query(Review)
|
||||
return query.all()
|
||||
|
||||
```
|
||||
Let's test to see if we are at the same point. Run `uvicorn app:app --reload` then perform a GET request for `/authors` endpoint. You should see two authors returned:
|
||||
|
||||
```sh
|
||||
|
||||
❯ curl -X 'GET' \
|
||||
'http://127.0.0.1:8000/authors' \
|
||||
-H 'accept: application/json' | jq
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Author 1",
|
||||
"books": [],
|
||||
"awards": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Author 2",
|
||||
"books": [],
|
||||
"awards": []
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Now, let's start implementing what's required to load different fields based on user input. First of all, we need to have a way to determine the relationships of our database models. Then we will use these relationships to generate pydantic schemas which represents loading options. We will then use these schemas as input to our endpoint and inside our endpoint, we will load required fields.
|
||||
|
||||
|
||||
1. Define a `RelationshipLoader` class in `models.py`.
|
||||
|
||||
```python
|
||||
from typing import Any
|
||||
from sqlalchemy.inspection import inspect
|
||||
from sqlalchemy.orm import (
|
||||
joinedload,
|
||||
selectinload,
|
||||
)
|
||||
|
||||
|
||||
class RelationshipLoader:
|
||||
@classmethod
|
||||
def get_relationships(cls) -> dict[str, Any]:
|
||||
relationships = cls._get_relationships()
|
||||
result = {}
|
||||
for key, strategy in relationships.items():
|
||||
if strategy.get("selectinload"):
|
||||
result[key] = selectinload(*strategy["selectinload"])
|
||||
else:
|
||||
result[key] = joinedload(*strategy["joinedload"])
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def _get_relationships(cls, exclude_classes=None) -> dict[str, Any]:
|
||||
if exclude_classes is None:
|
||||
exclude_classes = []
|
||||
|
||||
relationships = {}
|
||||
mapper = inspect(cls)
|
||||
for rel in mapper.relationships:
|
||||
if rel.mapper.class_ in exclude_classes:
|
||||
continue
|
||||
load_strategy = ( # if it is a one to one or many to one relationship we are loading it with selectinload strategy, else joinedload
|
||||
{"selectinload": [getattr(cls, rel.key)]}
|
||||
if rel.direction.name in ["MANYTOONE", "ONETOMANY"]
|
||||
else {"joinedload": [getattr(cls, rel.key)]}
|
||||
)
|
||||
relationships[rel.key] = load_strategy
|
||||
|
||||
# Recursively inspect nested relationships
|
||||
target_cls = rel.mapper.class_
|
||||
if issubclass(target_cls, RelationshipLoader):
|
||||
nested_relationships = target_cls._get_relationships(
|
||||
[*exclude_classes, cls] # excluding the current class because we don't want bidirectional relationships to create infinite loop
|
||||
)
|
||||
for nested_rel, nested_strategy in nested_relationships.items():
|
||||
((strategy_name, attr),) = load_strategy.items()
|
||||
((_, nested_attr),) = nested_strategy.items()
|
||||
relationships[f"{rel.key}.{nested_rel}"] = {strategy_name: [*attr, *nested_attr]}
|
||||
|
||||
return relationships
|
||||
|
||||
```
|
||||
|
||||
Alter the `Base` definition to inherit from `RelationshipLoader` class. With this way, all the other models inheriting from `Base` will be also subclass of `RelationshipLoader`.
|
||||
|
||||
```python
|
||||
|
||||
class Base(DeclarativeBase, RelationshipLoader):
|
||||
pass
|
||||
```
|
||||
|
||||
This is all we need to do for our sqlalchemy models. Now, let's implement the function for generating pydantic schemas dynamically.
|
||||
|
||||
```python
|
||||
# schemas.py
|
||||
|
||||
|
||||
from typing import Any
|
||||
from pydantic import create_model
|
||||
|
||||
def generate_pydantic_model(model_name, strategies: dict[str, Any]) -> type[BaseModel]:
|
||||
pydantic_fields = dict.fromkeys(strategies, (bool | None, None))
|
||||
return create_model(model_name, **pydantic_fields)
|
||||
```
|
||||
|
||||
And lastly, let's use this function in `app.py` to generate pydantic schemas and use it in our router:
|
||||
|
||||
```python
|
||||
# app.py
|
||||
|
||||
from schemas import generate_pydantic_model
|
||||
|
||||
AuthorRelationships = Author.get_relationships()
|
||||
AuthorLoadOptions = generate_pydantic_model("AuthorModel", AuthorRelationships)
|
||||
|
||||
ReviewRelationships = Review.get_relationships()
|
||||
ReviewLoadOptions = generate_pydantic_model("ReviewModel", ReviewRelationships)
|
||||
|
||||
|
||||
@app.post("/authors", response_model=list[AuthorSchema])
|
||||
async def get_authors(options: AuthorLoadOptions):
|
||||
session = Session(engine)
|
||||
query = session.query(Author)
|
||||
for field, value in options:
|
||||
if value:
|
||||
query = query.options(AuthorRelationships[field])
|
||||
return query.all()
|
||||
|
||||
|
||||
@app.post("/reviews", response_model=list[ReviewSchema])
|
||||
async def get_reviews(options: ReviewLoadOptions):
|
||||
session = Session(engine)
|
||||
query = session.query(Review)
|
||||
for field, value in options:
|
||||
if value:
|
||||
query = query.options(ReviewRelationships[field])
|
||||
return query.all()
|
||||
|
||||
```
|
||||
|
||||
And that's all! If everything went fine, you should be able to load your database models with whatever fields you like:
|
||||
|
||||
```sh
|
||||
❯ curl -X 'POST' \
|
||||
'http://127.0.0.1:8000/authors' \
|
||||
-H 'accept: application/json' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"awards": true,
|
||||
"books": false,
|
||||
"books.reviews": false
|
||||
}' | jq
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Author 1",
|
||||
"books": [],
|
||||
"awards": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Author 2",
|
||||
"books": [],
|
||||
"awards": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Award 1",
|
||||
"year": 2021
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Award 2",
|
||||
"year": 2024
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
❯ curl -X 'POST' \
|
||||
'http://127.0.0.1:8000/reviews' \
|
||||
-H 'accept: application/json' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"book": true,
|
||||
"book.author": true,
|
||||
"book.author.awards": false
|
||||
}' | jq
|
||||
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"text": "Review 1",
|
||||
"book_id": 1,
|
||||
"book": {
|
||||
"id": 1,
|
||||
"title": "Book 1",
|
||||
"author_id": 1,
|
||||
"author": {
|
||||
"id": 1,
|
||||
"name": "Author 1",
|
||||
"books": [],
|
||||
"awards": []
|
||||
},
|
||||
"reviews": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"text": "Review 2",
|
||||
"book_id": 1,
|
||||
"book": {
|
||||
"id": 1,
|
||||
"title": "Book 1",
|
||||
"author_id": 1,
|
||||
"author": {
|
||||
"id": 1,
|
||||
"name": "Author 1",
|
||||
"books": [],
|
||||
"awards": []
|
||||
},
|
||||
"reviews": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"text": "Review 3",
|
||||
"book_id": 3,
|
||||
"book": {
|
||||
"id": 3,
|
||||
"title": "Book 3",
|
||||
"author_id": 2,
|
||||
"author": {
|
||||
"id": 2,
|
||||
"name": "Author 2",
|
||||
"books": [],
|
||||
"awards": []
|
||||
},
|
||||
"reviews": []
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
```
|
||||
|
||||
You may notice that our endpoints are now accepting POST request. If you want to perform the same thing with GET request, you will need to convert the options to query params. I will explain how it can be done in my next post. Stay tuned!
|
@ -1,15 +1,15 @@
|
||||
---
|
||||
layout: single
|
||||
title: About
|
||||
classes: wide
|
||||
permalink: /about/
|
||||
---
|
||||
|
||||
Hi, my name is **Şahin Akkaya**. I am a 4th year student studying
|
||||
Computer Engineering at [ITU][itu]. I am a Free Software enthusiast,
|
||||
Python lover and perfectionist. I like to tinker things until they
|
||||
are *just right*. I also believe there is no such thing as perfect so
|
||||
I never stop. I will do my best to make things better and I love doing
|
||||
it so far.
|
||||
Hi, my name is **Şahin Akkaya**. I am a Computer Engineer graduated
|
||||
from [ITU][itu]. I am a Free Software enthusiast, Python lover and
|
||||
perfectionist. I like to tinker things until they are *just right*.
|
||||
I also believe there is no such thing as perfect so I never stop.
|
||||
I will do my best to make things better and I love doing it so far.
|
||||
|
||||
> Roses are red \\
|
||||
Violets are blue \\
|
||||
|
BIN
assets/images/sqlalchemy/ring.jpg
Normal file
BIN
assets/images/sqlalchemy/ring.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 77 KiB |
BIN
assets/images/sqlalchemy/schema.png
Normal file
BIN
assets/images/sqlalchemy/schema.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 54 KiB |
@ -1,6 +1,7 @@
|
||||
---
|
||||
layout: single
|
||||
title: Contact
|
||||
classes: wide
|
||||
permalink: /contact/
|
||||
---
|
||||
You can contact me via:
|
||||
|
@ -3,5 +3,6 @@
|
||||
# To modify the layout, see https://jekyllrb.com/docs/themes/#overriding-theme-defaults
|
||||
|
||||
layout: home
|
||||
classes: wide
|
||||
---
|
||||
|
||||
|
Reference in New Issue
Block a user