Skip to content

Instantly share code, notes, and snippets.

View TheBigRoomXXL's full-sized avatar
⚗️
experimenting

TheBigRoomXXL TheBigRoomXXL

⚗️
experimenting
View GitHub Profile
@TheBigRoomXXL
TheBigRoomXXL / no_expire_on_commit.py
Last active April 12, 2023 07:28
Flask-SQLAchemy Session without expire_on_commit
""" Usefull before 2.0 when serializing object after commit, now you should use *returning* """
from contextlib import contextmanager
# More details here: https://stackoverflow.com/a/51452451
@contextmanager
def no_expire():
"""Provide db.session with the expire_on_commit set to False only this time."""
s = db.session()
s.expire_on_commit = False
@TheBigRoomXXL
TheBigRoomXXL / traced.py
Last active April 7, 2023 07:13
Tracing decorator for OpenTelemetry
# Inspired by https://stackoverflow.com/a/309000
# With some help for typing from https://rednafi.github.io/reflections/static-typing-python-decorators.html
from functools import wraps
from collections.abc import Callable
from typing import ParamSpec, TypeVar
from opentelemetry import trace
P = ParamSpec("P")
@TheBigRoomXXL
TheBigRoomXXL / SQLPagination.py
Last active April 7, 2023 07:07
SQL Cursor for Flask-SQLAlchemy and Flask-Smorest
from flask_smorest import Api, Blueprint
from flask_sqlalchemy.query import Query
class SQLCursor():
"""Automatically paginate a Query object return by a view"""
def __init__(self, query:Query, page_params):
self.page_params = page_params
self.result = query.paginate(
page=page_params.page,
@TheBigRoomXXL
TheBigRoomXXL / sqlachemy_patch.py
Last active April 7, 2023 07:05
Flask-SQLAlchemy patch method
from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy.model import Model
class MyDbModel(Model):
"""MyDbModel is used as the "model_class" of db (aka db.Model).
Extend the SQLAlchemy functionalities throught this class."""
def patch(self, update_dictionary: dict) -> None:
"""Partial update of an object with a simple and clear syntax"""