Skip to content

Instantly share code, notes, and snippets.

@rednafi
rednafi / worklog.md
Last active August 20, 2024 07:14
Generate a simple worklog.

What

The following script will generate a simple markdown worklog in the format listed below. It correctly handles the partial weeks at the beginning and the end of the year.

# Worklog

## Week 1 [2025-01-01 - 2025-01-03]
@trvswgnr
trvswgnr / run-concurrent-async.ts
Created July 17, 2023 09:34
generic concurrent execution
export async function runConcurrentAsync<T, A extends IterableIterator<unknown>>(tasks: Task<T>[], argsList: A[] = [], concurrency = 5): Promise<T[]> {
const semaphore = new Semaphore(concurrency);
const promises = tasks.map(async (task, index) => {
await semaphore.acquire();
try {
const args = argsList[index] || [];
return await task(...args);
} finally {
semaphore.release();
}
@hwayne
hwayne / script.py
Created March 13, 2023 19:59
Script that notifies me when a cubs game is happening
# This is running on an aws lambda instance with a CloudWatch trigger:
# Trigger is cron(0 17 * * ? *)
# CSV is from https://www.mlb.com/cubs/schedule/downloadable-schedule
import json
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from os import getenv
from csv import DictReader
from datetime import datetime
import trio
async def main():
async with ws_connect("ws://127.0.0.1:8765") as websockets:
await websockets.send("Hello, world.")
message = await websockets.recv()
print(message)
trio.run(main)
@corlaez
corlaez / README.md
Last active March 18, 2025 15:33
Hexagonal Architecture and Modular Implementation

Hexagonal Architecture

Conceptualized by Alistair Cockburn. Also known as "Ports and Adapters".

In a nutshell:

Application Driver -> Primary Adapter -> Primary Port -> Use Case -> Secondary Port -> Secondary Adapter -> External System/Side Effect
@Kludex
Kludex / main.py
Last active April 17, 2024 01:55
Document each version on FastAPI
from fastapi import APIRouter, FastAPI
from utils import create_versioning_docs
app = FastAPI(docs_url=None, redoc_url=None)
v1_router = APIRouter(prefix="/v1")
v2_router = APIRouter(prefix="/v2")
@Kludex
Kludex / main.py
Last active March 19, 2025 17:07
Run Gunicorn with Uvicorn workers in code
""" Snippet that demonstrates how to use Gunicorn with Uvicorn workers in code.
Feel free to run:
- `python main.py` - to use uvicorn.
- `ENV=prod python main.py` - to use gunicorn with uvicorn workers.
Reference: https://docs.gunicorn.org/en/stable/custom.html
"""
@jordanisaacs
jordanisaacs / sessioncookie.py
Created April 3, 2021 22:13
Basic implementation with example of a FastAPI SessionCookie (compatible with OpenAPI and dependency injection)
from datetime import timedelta, datetime
from typing import Type, Optional, Dict, Any, Tuple
from uuid import uuid4
from abc import ABC, abstractmethod
from fastapi import FastAPI, Request, Depends, HTTPException, Response
from fastapi.security.api_key import APIKeyBase, APIKey, APIKeyIn
from base64 import b64encode, b64decode
from itsdangerous import TimestampSigner
from itsdangerous.exc import BadTimeSignature, SignatureExpired
@sandys
sandys / Fastapi-sqlalchemy-pydantic-dataclasses-reloadable-logging.md
Last active June 30, 2024 09:23
fastapi with python 3.10 dataclasses - used to create both sqlalchemy and pydantic models simultaneously. And setting up sqlalchemy the right way (without deadlocks or other problems). Additionally, this also takes care of unified logging when running under gunicorn..as well as being able to run in restartable mode.
@Hultner
Hultner / bound_base_conditional.py
Created March 5, 2021 12:28
Use assignment with bound TypeVar in conditional.
from typing import Type, TypeVar
class Base:
common: str = "Data"
class ImportModel(Base):
pass