Compare commits

...

12 Commits

Author SHA1 Message Date
f1edcb8e54 Fix an error 2024-08-05 16:35:26 +03:00
a6aff36585 Fix an error 2024-08-05 10:07:49 +03:00
2cc8af0fef Change layout 2024-08-04 21:17:25 +03:00
9b24962de9 Change layout 2024-08-04 21:13:42 +03:00
92703a333b Fix 2024-08-04 20:22:34 +03:00
4e382fe353 Fix 2024-08-04 20:00:02 +03:00
8f03ab7a18 Fix 2024-08-04 19:56:58 +03:00
d1ff601e9b Fix 2024-08-04 19:53:17 +03:00
851938dd13 Fix 2024-08-04 19:44:35 +03:00
5b278d9491 Fix 2024-08-04 19:24:38 +03:00
a4bc6b1eed Fix 2024-08-04 19:10:20 +03:00
5d86fb7c4a Fix 2024-08-04 17:59:14 +03:00
16 changed files with 55 additions and 33 deletions

View File

@ -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>

View File

@ -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

View File

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

View File

@ -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:
---

View File

@ -1,6 +1,7 @@
---
title: "Creating a *Useless* User"
date: 2022-02-27 16:40:00 +0300
classes: wide
tags: linux permissions privileges
---
## Story

View File

@ -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
---

View File

@ -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
---

View File

@ -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
---

View File

@ -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/)

View File

@ -1,5 +1,6 @@
---
title: "Recap of 2022"
classes: wide
date: 2022-12-29 23:22:08 +0300
---

View File

@ -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
---

View File

@ -1,17 +1,17 @@
---
title: "Conditionally load SQLAlchemy model relationships in FastAPI"
date: 2024-08-04 12:55:00 +0300
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.)
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.
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.
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!
![One endpoint to rule them all](/assets/images/sqlalchemy/ring.jpg)
@ -178,17 +178,37 @@ async def get_authors():
async def get_reviews():
session = Session(engine)
query = session.query(Review)
result = query.all()
return result
return query.all()
```
Let's test to see if we are at the same point. Run `uvicorn app:app --reload` then go to `http://127.0.0.1:8000/docs`. If everything went correctly you should see two authors returned when you perform a GET request on `/authors` endpoint.
![Example result](/assets/images/sqlalchemy/res.png)
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
@ -223,7 +243,7 @@ class RelationshipLoader:
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)}
else {"joinedload": [getattr(cls, rel.key)]}
)
relationships[rel.key] = load_strategy
@ -234,12 +254,9 @@ class RelationshipLoader:
[*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():
# if it is a nested relationship, I am assuming it should be loaded with selectinload.
# i don't know a better way to handle this but this is working fine for us.
combined = load_strategy["selectinload"].copy()
combined.extend(nested_strategy["selectinload"])
combined = {"selectinload": combined}
relationships[f"{rel.key}.{nested_rel}"] = combined
((strategy_name, attr),) = load_strategy.items()
((_, nested_attr),) = nested_strategy.items()
relationships[f"{rel.key}.{nested_rel}"] = {strategy_name: [*attr, *nested_attr]}
return relationships
@ -260,21 +277,14 @@ This is all we need to do for our sqlalchemy models. Now, let's implement the fu
from typing import Any
from models import RelationshipLoader
from pydantic import create_model
def generate_load_strategies(sqlalchemy_model: type[RelationshipLoader]) -> dict[str, Any]:
return sqlalchemy_model.get_relationships()
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 these functions in `app.py` to generate pydantic schemas and use it in our router:
And lastly, let's use this function in `app.py` to generate pydantic schemas and use it in our router:
```python
# app.py
@ -305,15 +315,14 @@ async def get_reviews(options: ReviewLoadOptions):
for field, value in options:
if value:
query = query.options(ReviewRelationships[field])
result = query.all()
return result
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 -S -X 'POST' \
curl -X 'POST' \
'http://127.0.0.1:8000/authors' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \

View File

@ -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 \\

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

View File

@ -1,6 +1,7 @@
---
layout: single
title: Contact
classes: wide
permalink: /contact/
---
You can contact me via:

View File

@ -3,5 +3,6 @@
# To modify the layout, see https://jekyllrb.com/docs/themes/#overriding-theme-defaults
layout: home
classes: wide
---