Skip to content

Instantly share code, notes, and snippets.

View daaniam's full-sized avatar

dan daaniam

  • San Diego, CA
  • 22:19 (UTC -07:00)
View GitHub Profile
@daaniam
daaniam / pycharm_formatters.txt
Last active August 22, 2022 10:04
PyCharm formatters (black, isort)
Black watcher:
Program: $PyInterpreterDirectory$/black
Arguments: $FilePath$
Output paths to refresh: $FilePath$
Working directory: $ProjectFileDir$
iSort watcher:
Program: $PyInterpreterDirectory$/isort
Arguments: $FilePath$
Output paths to refresh: $FilePath$
@daaniam
daaniam / extract_from_xml.py
Last active December 6, 2022 14:22
example: Locate xml element
def extract_files_from_xml(xml_element: etree.Element) -> list[BytesIO]:
"""Extract files from XML element"""
output = []
elements_with_file = ["bArray", "ByteArray"]
for file_element in elements_with_file:
# Locate element
@daaniam
daaniam / run_in_container.py
Created December 6, 2022 14:21
Run script in container
def run_script_in_container(script_name: str, console_output: bool = False) -> str | None:
"""Run script within the devcontainer to gather application metadata."""
# Add Python file suffix if not present
if script_name[-3:] != ".py":
script_name = f'{script_name}.py'
# Command
cmd = ['python', f'/workspace/scripts/{script_name}']
@daaniam
daaniam / compose_multiple-cmds.yaml
Created December 6, 2022 14:30
docker compose run multiple commands
command:
[
"/bin/sh",
"-c",
"cd /workspace ; poetry install ; while sleep 1000; do :; done"
]
@daaniam
daaniam / sql_alchemy_base_mixin.py
Created February 15, 2023 16:11
SQL Alchemy custom Base with Mixins
from sqlalchemy import TIMESTAMP, UUID, Column
from sqlalchemy.orm import declarative_mixin
from sqlalchemy.orm import declarative_base
# MIXINS:
@declarative_mixin
class IDMixin:
id = Column(UUID, primary_key=True)
@daaniam
daaniam / example.md
Created March 31, 2023 23:37
FastAPI: Pydantic's BaseSettings injection for pytest

FastAPI: Pydantic's BaseSettings injection for pytest


There are a few options how to change app config for tests. According to FastAPI docs, it's recommended to use `dependency_overrides`, but there might be a case where we need to change the entire app settings (using Pydantic's BaseSettings here).

config.py

@daaniam
daaniam / basic_state_class.py
Created April 4, 2023 06:13
Basic state class
import json
class TState:
def __new__(cls):
if not hasattr(cls, "instance"):
cls.instance = super(TState, cls).__new__(cls)
return cls.instance
def add(self, name, value):
setattr(self, name, value)
@daaniam
daaniam / pydantic_sqlalchemy_models.md
Created April 13, 2023 06:08
Pydantic schema from SQLAlchemy model (inheritance)
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from pydantic.dataclasses import dataclass

# Create engine and session
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()
@daaniam
daaniam / pydantic_set_env_prefix.md
Last active April 17, 2023 04:05
Pydantic set env_prefix

Add (set_prefix) method to your settings class...

class MyConfig(BaseSettings):
    logging_level: str = "example"

    @classmethod
    def set_prefix(cls, prefix: str):
        cls.__config__.env_prefix = prefix
 for field in cls.__fields__.values():
@daaniam
daaniam / alembic_async.py
Last active May 3, 2023 04:45
Alembic .env config AsyncEngine
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import AsyncEngine
from app.core.config import get_config
app_config = get_config()
config.set_main_option("sqlalchemy.url", app_config.postgres.dsn)